note 69370 modified in language.oop5.overloading by danbrown

From: Date: Fri, 14 Nov 2008 17:16:34 +0000
Subject: note 69370 modified in language.oop5.overloading by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-146544@lists.php.net to get a copy of this message
<?php $myclass->foo['bar'] = 'baz'; ?> When overriding __get and __set, the above code can work (as expected) but it depends on your __get implementation rather than your __set. In fact, __set is never called with the above code. It appears that PHP (at least as of 5.1) uses a reference to whatever was returned by __get. To be more verbose, the above code is essentially identical to: <?php $tmp_array = &$myclass->foo; $tmp_array['bar'] = 'baz'; unset($tmp_array); ?> Therefore, the above won't do anything if your __get implementation resembles this: <?php function __get($name) { return array_key_exists($name, $this->values) ? $this->values[$name] : null; } ?> You will actually need to set the value in __get and return that, as in the following code: <?php function __get($name) { if (!array_key_exists($name, $this->values)) $this->values[$name] = null; return $this->values[$name]; } ?> --was-- $myclass->foo['bar'] = 'baz'; When overriding __get and __set, the above code can work (as expected) but it depends on your __get implementation rather than your __set. In fact, __set is never called with the above code. It appears that PHP (at least as of 5.1) uses a reference to whatever was returned by __get. To be more verbose, the above code is essentially identical to: $tmp_array = &$myclass->foo; $tmp_array['bar'] = 'baz'; unset($tmp_array); Therefore, the above won't do anything if your __get implementation resembles this: function __get($name) { return array_key_exists($name, $this->values) ? $this->values[$name] : null; } You will actually need to set the value in __get and return that, as in the following code: function __get($name) { if (!array_key_exists($name, $this->values)) $this->values[$name] = null; return $this->values[$name]; } http://php.net/manual/en/language.oop5.overloading.php

« previous php.notes (#146544) next »