note 81006 added to language.oop5.overloading
| From: | dave at mozaiq dot org | Date: | Sun, 10 Feb 2008 23:58:24 +0000 |
| Subject: | note 81006 added to language.oop5.overloading | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-136015@lists.php.net to get a copy of this message | ||
Several users have mentioned ways to allow setting of array properties via magic methods. In
particular, PHP calls the __get() method instead of the __set() method when you try to do:
$obj->prop['offset'] = $val.
The suggestions that I've read below all work, except that they do not allow you make
properties read-only. After a bit of struggling, I have found a solution. Essentially, if the
property is supposed to be a read-only array, create an new ArrayObject() out of it, then clone it
and return the clone.
<?php
public function __get($var) {
if(isset($this->read_only_props[$var])) {
$ret = null;
if (is_array($this->read_only_props[$var]))
return clone new ArrayObject($this->read_only_props[$var]);
else if (is_object($this->read_only_props[$var]))
return clone $this->read_only_props[$var];
else
return $this->read_only_props[$var];
}
else if (!isset($this->writeable_props[$var]))
$this->writeable_props[$var] = NULL;
return $this->writeable_props[$var];
}
public function __set($var, $val) {
if (isset($this->read_only_props[$var]))
throw new Exception('tried to set a read only property on the event object');
return $this->writeable_props[$var] = $val;
}
?>
Note that __get() does not explicitly return by reference as many examples have suggested. Also, I
have not found a way to detect when __get() is being called for setting purposes, thus my code can
not throw an exception when necessary in these cases.
----
Server IP: 209.41.74.194
Probable Submitter: 24.218.222.170
----
Manual Page -- http://www.php.net/manual/en/language.oop5.overloading.php
Edit -- https://master.php.net/note/edit/81006
Del: integrated -- https://master.php.net/note/delete/81006/integrated
Del: useless -- https://master.php.net/note/delete/81006/useless
Del: bad code -- https://master.php.net/note/delete/81006/bad+code
Del: spam -- https://master.php.net/note/delete/81006/spam
Del: non-english -- https://master.php.net/note/delete/81006/non-english
Del: in docs -- https://master.php.net/note/delete/81006/in+docs
Del: other reasons-- https://master.php.net/note/delete/81006
Reject -- https://master.php.net/note/reject/81006
Search -- https://master.php.net/manage/user-notes.php