note 99058 added to language.oop5.magic
| From: | Anonymous at osu1 dot php dot net | Date: | Sun, 25 Jul 2010 02:41:41 +0000 |
| Subject: | note 99058 added to language.oop5.magic | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-171109@lists.php.net to get a copy of this message | ||
Concerning __set() with protected/private/overloaded properties, the behavior might not be so
intuitive without knowing some underlying rules. Consider this test object for the following
examples...
<?php
class A {
protected $test_int = 2;
protected $test_array = array('key' => 'test');
protected $test_obj;
function __construct() {
$this->test_obj = new stdClass();
}
function __get($prop) {
return $this->$prop;
}
function __set($prop, $val) {
$this->$prop = $val;
}
}
$a = new A();
?>
Combined Operators (.=, +=, *=, etc): you must also define a companion __get() method to grant write
-and- read access to the property. Remember, "$x += $y" is shorthand for "$x = $x +
$y". In other words, "__set($x, (__get($x) + $y))".
Properties that are Arrays: attempting to set array values like "$a->test_array[] =
'asdf';" from outside this object will result in an "Indirect modification of
overloaded property" notice and the operation completely ignored. You can't use
'[]' for array value assignment in this context (with the exception only if you made
__get() return by reference, in which case, it would work fine and bypass the __set() method
altogether). You can work around this doing something like unioning the array instead:
<?php
$a->test_array[] = 'asdf'; // notice given and ignored unless __get() was declared to
return by reference
$a->test_array += array(1 => 'asdf'); // to add a key/value
$a->test_array = array("key" => 'asdf') + $a->test_array; // to
overwrite a key/value.
?>
Properties that are Objects: as long as you have that __get() method, you can freely access and
alter that sub object's own properties, bypassing __set() entirely. Remember, objects are
assigned and passed by reference naturally.
<?php
$a->test_obj->prop = 1; // fine if $a did not have a set method declared.
?>
All above tested in 5.3.2.
----
Server IP: 69.147.83.197
Probable Submitter: 70.124.94.109
----
Manual Page -- http://www.php.net/manual/en/language.oop5.magic.php
Edit -- https://master.php.net/note/edit/99058
Del: integrated -- https://master.php.net/note/delete/99058/integrated
Del: useless -- https://master.php.net/note/delete/99058/useless
Del: bad code -- https://master.php.net/note/delete/99058/bad+code
Del: spam -- https://master.php.net/note/delete/99058/spam
Del: non-english -- https://master.php.net/note/delete/99058/non-english
Del: in docs -- https://master.php.net/note/delete/99058/in+docs
Del: other reasons-- https://master.php.net/note/delete/99058
Reject -- https://master.php.net/note/reject/99058
Search -- https://master.php.net/manage/user-notes.php