__get() and __set() in PHP 5

php.internals

Paul Hudson

23 years ago
All, I've been poking around with these two functions while testing the build from CVS, and am not sure how they're supposed to work. From what I can gather, they are only called when changing a variable that wasn't in the class definition. I say that because I took the example script from http://uk.php.net/zend-engine-2.php and stripped it down to this: <?php class Setter { public $n; public $z; function __get($nm) { print "Getting [$nm]\n"; } function __set($nm, $val) { print "Setting [$nm] to $val\n"; } } $foo = new Setter(); $foo->n = 1; $foo->z++; $foo->z++; ?> That script outputs nothing, despite reading and writing to z twice, and writing to n once. If you comment out the "public $n;" and "public $z;" lines, you get the following output: Setting [n] to 1 Getting [z] Setting [z] to 1 Getting [z] Setting [z] to 1 ... which is what I was expecting. Are __get() and __set(), then, only supposed to work with non-declared variables, or am I doing something wrong? Thanks, --Paul

Andi Gutmans

23 years ago
Yes, you are right. They only work if the variable is not defined. Andi At 08:03 PM 12/7/2003 +0100, Paul Hudson wrote:

Paul Hudson

23 years ago
Andi, Wouldn't it be more useful if they worked for all variables, or is there a design reason why they work as they do currently? --Paul

Andi Gutmans

23 years ago
At 08:42 PM 12/7/2003 +0100, Paul Hudson wrote:
>Andi, > >Wouldn't it be more useful if they worked for all variables, or is there a >design reason why they work as they do currently?
The idea is that you can mix regular variables and variable overloading, it is like this by design. If you want it to work for all variables then just don't declare them and handle their storage on your own in an object local array. Andi