Questions about overloading and visibility in PHP5

From: Date: Tue, 18 Sep 2007 17:17:54 +0000
Subject: Questions about overloading and visibility in PHP5
Groups: php.general 
Request: Send a blank email to php-general+get-262209@lists.php.net to get a copy of this message
I've been doing a bunch of reading about objects and overloading in PHP5, but I've got a couple of questions that I can't seem to find the answer to online. Suppose the following code in PHP5.2.4: <?php class foo { public $x; private $z = 'z'; public function __set ($name, $val) { echo "Setting \$this->$name to $val...\n"; $this->{$name} = $val; } public function __get ($name) { return "The value of $name is {$this->{$name}}.\n"; } } ?> My questions are as follows: 1) It seems that the getter and setter are not called on every single call. For example, if I do the following: $bar = new foo; $bar->x = 'x'; There is no output. I would expect to see "Setting $this->x to x." Another example: $bar = new foo; $bar->y = 'y'; echo $bar->y; I would expect this to see "The value of y is y." but instead I just get 'y' as output. So when do the various setters/getters get used? 2) It seems that getters ignore the visibility of properties. Why is this? For example: $bar = new foo; echo $bar->z; I would expect this to throw an error about accessing a private member, but it outputs "The value of z is z." just fine. If I remove the __get() overloader, an error is thrown. I'm guessing that the answer to all of my questions is some how wrapped up in visibility and overloading. Unfortunately I cannot find any resource that documents the interactions. TIA.

« previous php.general (#262209) next »