Re: "Bless"ing an object
| From: | Greg Beaver | Date: | Fri, 28 Nov 2003 20:29:24 +0000 |
| Subject: | Re: "Bless"ing an object | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-171303@lists.php.net to get a copy of this message | ||
Hi Wouter,
The only disadvantage to assigning to $this is that it may not be supported in PHP 5 - php-internals discussion has described it as a bad idea. I would get beta 2 and test it out, see what happens.
Incidentally, you don't need to unset new, and I would use
$this =& $New;
Regards,
Greg
Wouter van Vliet wrote:
Greg Beaver wrote:Wouter, you could try this adding this method to each object you need blessings from: function &bless($classname) {Thanks Greg .. this comes pretty close to what I had done myself as a workaround. Only thing that's different is that in my bless implementation I don't return the blessed value, but overwrite the $this var. Which works. What advantage do you think I would get from your appraoch? [snip The Way I Bless {example from own memory, cannot reach the actual code at this time} ] function Bless($ClassName) { // return false if class doesn't exist if (!class_exists($ClassName)) return false; $New = new $ClassName(); foreach($this as $Key => $Value) $New[$Key] = $Value; $this = $New; unset $New); } [/snip The Way I Bless] Hmm .. maybe I'm thinking 'out of te box' here, but can I manually add this functionality to stdClass, so that they are available in each and ever object I create?if ($classname == get_class($this)) { return $this; } $vars = get_object_vars($this); $ret = new $classname; return $ret->loadValues($vars);} function &loadValues($vals) {foreach ($vals as $name => $val) { $this->$name = $val; } return $this;} In the Load() method, you should determine what class you need, and call $ret = &$this->bless('classname'), and then return $ret. Then, instead of doing $Thing->Load(); do $Thing = &$Thing->Load(); and have Load() return an object instance (either $this or the newly blessed object). This will maintain encapsulation and achieve the results you're looking for. Regards, Greg