note 90985 added to language.oop5.overloading

From: Date: Tue, 19 May 2009 19:17:41 +0000
Subject: note 90985 added to language.oop5.overloading
Groups: php.notes 
Request: Send a blank email to php-notes+get-155753@lists.php.net to get a copy of this message
Just another note about using __get() & __set() on array properties with PHP v5.2.0. Took me quite a while to find out why I couldn't write an array property that was created via __set(). Now a few notes earlier someone described a working solution using the ArrayObject-class. This does work, but has a big downside, you cannot expect other programmers to know that they will be getting an instance of ArrayObject instead of a native array, and trying to do an implode() on an ArrayObject will just not work. So, here is my solution to the problem: class A { private $properties = array(); public function __set($key, $value) { if (is_array($value)) { $this->$key = $value; } else { $this->properties[$key] = $value; } } public function __get($key) { if (array_key_exists($key, $this->properties)) { return $this->properties[$key]; } return null; } } The idea behind this is, that you can register new properties at any time from within a class without getting a warning or some of that kind. Now, if you try to set a property from outside the class, the __set() method will be called and decides whether to place the new property in the properties array or declare it as a new "native" property. When trying to get that property, the __get() method will only be called if the property is not "native", which won't be the case for an array. HTH ---- Server IP: 216.92.131.65 Probable Submitter: 62.245.202.66 ---- Manual Page -- http://www.php.net/manual/en/language.oop5.overloading.php Edit -- https://master.php.net/note/edit/90985 Del: integrated -- https://master.php.net/note/delete/90985/integrated Del: useless -- https://master.php.net/note/delete/90985/useless Del: bad code -- https://master.php.net/note/delete/90985/bad+code Del: spam -- https://master.php.net/note/delete/90985/spam Del: non-english -- https://master.php.net/note/delete/90985/non-english Del: in docs -- https://master.php.net/note/delete/90985/in+docs Del: other reasons-- https://master.php.net/note/delete/90985 Reject -- https://master.php.net/note/reject/90985 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#155753) next »