note 72756 added to language.oop5.overloading
| From: | james at thunder-removeme-monkey dot net | Date: | Wed, 31 Jan 2007 21:07:33 +0000 |
| Subject: | note 72756 added to language.oop5.overloading | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-122436@lists.php.net to get a copy of this message | ||
Following up on the comment by "jstubbs at work-at dot co dot jp" and after reading
"http://weierophinney.net/matthew/archives/
131-Overloading-arrays-in-PHP-5.2.0.html", the following methods handle property overloading
pretty neatly and return variables in read/write mode.
<?php
class View {
/* Somewhere to store our overloaded properties */
private $v = array();
/* Store a new property */
function __set($varName, $varValue) {
$this->v[$varName] = $varValue;
}
/* Retrieve a property */
function __get($varName) {
if(!isset($this->v[$varName])) {
$this->v[$varName] = NULL;
}
return is_array($this->v[$varName]) ? new ArrayObject($this->v[$varName]) :
$this->v[$varName];
}
}
?>
This is an amalgm of previous solutions with the key difference being the use of ArrayObject in the
return value. This is more flexible than having to extend the whole class from ArrayObject.
Using the above class, we can do ...
<?php
$obj = new SomeOtherObject();
$view = new View();
$view->list = array();
$view->list[] = "hello";
$view->list[] = "goat";
$view->list[] = $group;
$view->list[] = array("a", "b", "c");
$view->list[3][] = "D";
$view->list[2]->aprop = "howdy";
/*
$view->list now contains:
[0] => "hello"
[1] => "goat"
[2] => SomeOtherObject { aprop => "howdy" }
[3] => array("a", "b", "c", "D")
and
$obj === $view->list[2] // equates to TRUE
*/
?>
----
Server IP: 83.138.144.80
Probable Submitter: 82.39.155.185
----
Manual Page -- http://www.php.net/manual/en/language.oop5.overloading.php
Edit -- https://master.php.net/note/edit/72756
Del: integrated -- https://master.php.net/note/delete/72756/integrated
Del: useless -- https://master.php.net/note/delete/72756/useless
Del: bad code -- https://master.php.net/note/delete/72756/bad+code
Del: spam -- https://master.php.net/note/delete/72756/spam
Del: non-english -- https://master.php.net/note/delete/72756/non-english
Del: in docs -- https://master.php.net/note/delete/72756/in+docs
Del: other reasons-- https://master.php.net/note/delete/72756
Reject -- https://master.php.net/note/reject/72756
Search -- https://master.php.net/manage/user-notes.php