PLDB
Languages Features Calendar CSV Lists Blog About Sponsor Add Language
GitHub icon

Magic Getters and Setters

Magic Getters and Setters

Magic Getters and Setters are a feature.

Magic getters and setters are a feature in some object-oriented languages that allows you to define a function that will be called when an undefined property on the instance is called in either a getting or setting manner.


Languages without Magic Getters and Setters include C++

Languages with Magic Getters and Setters include JavaScript, PHP

Example from JavaScript:
// Can be implemented in ES6 using proxies: "use strict"; if (typeof Proxy == "undefined") { throw new Error("This browser doesn't support Proxy"); } let original = { "foo": "bar" }; let proxy = new Proxy(original, { get(target, name, receiver) { let rv = Reflect.get(target, name, receiver); if (typeof rv === "string") { rv = rv.toUpperCase(); } return rv; } }); console.log(`original.foo = ${original.foo}`); // "original.foo = bar" console.log(`proxy.foo = ${proxy.foo}`); // "proxy.foo = BAR"
Example from PHP:
public function __set($name, $value) { echo "Setting '$name' to '$value'\n"; $this->data[$name] = $value; } public function __get($name) { echo "Getting '$name'\n"; if (array_key_exists($name, $this->data)) { return $this->data[$name]; } $trace = debug_backtrace(); trigger_error( 'Undefined property via __get(): ' . $name . ' in ' . $trace[0]['file'] . ' on line ' . $trace[0]['line'], E_USER_NOTICE); return null; }
implicit-type-casting-feature.html 路 magic-getters-and-setters-feature.html 路 merges-whitespace-feature.html

View source

PLDB - Build the next great programming language 路 v2022 Day 33 Docs Build Acknowledgements Traffic Today Traffic Trends Mirrors GitHub feedback@pldb.com