Re: "Bless"ing an object
| From: | Greg Beaver | Date: | Wed, 26 Nov 2003 14:49:17 +0000 |
| Subject: | Re: "Bless"ing an object | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-171074@lists.php.net to get a copy of this message | ||
Wouter,
you could try this adding this method to each object you need blessings from:
function &bless($classname)
{
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
Wouter Van Vliet wrote:
Hi Folks I was wondering (mostly because I came across some situations where I need it) if PHP supplies any methods to "bless" an array or object to become some other object. In perl, I can simply do: my $SomeInstance = bless { item => 'value', 'Item2' => 'value2' }, 'SomeObject'; And then if I decide that $SomeInstance should be an intance of some other object: bless $SomeInstance, 'OtherObject'; In PHP it would be extremely useful for for doing something like this: <?php Class Foo { Load() { ( .. ) } }; Class Bar extends Foo { } $Thing = new Foo(); $Thing->Load(); ?> In Load the object data is loaded from the database, and now imagine one row to contain the subclass this instance of Foo should become. I then would want $Thing to become and thus behave like an instance of Bar (if my database row says so). Hope this message wasn't too confusing ;) Wouter