note 35349 added to ref.classobj
| From: | ar at rack1 dot php dot net | Date: | Thu, 28 Aug 2003 12:59:00 +0000 |
| Subject: | note 35349 added to ref.classobj | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-55228@lists.php.net to get a copy of this message | ||
I missed some kind of function to dynamicly override or extend an Object:
-----------------------------------------
function &extendObj(&$obj, $code) {
static $num = 0;
$classname = get_class($obj);
$newclass = $classname.$num;
eval('class '.$newclass.' extends '.$classname.' { '.$code.'
}');
$newobj = new $newclass();
$vars = get_class_vars($classname);
foreach($vars AS $key=>$value) {
$newobj->$key = &$obj->$key;
}
return $newobj;
}
-----------------------------------------
This creates a new class which extends the old one by the given code parameter, instanciates it and
copy all vars from the old obj to the new one.
-----------------------------------------
class testA {
var $prop = 'a';
function funcA($val) {
$this->prop = $val;
}
function value() {
return $this->prop;
}
}
$obj = new testA();
$newobj = &extendObj(&$obj, 'function addX() { $this->prop .= "x";
}');
$newobj->funcA('abc');
$newobj->addX();
echo $newobj->value();
-----------------------------------------
Results in 'abcx'. You can use the function multiple times and also with class variables.
Be carefull, even if $newobj is just a copy of $obj, $obj->value() will return 'abcx',
too, because of the & operator: $newobj->$key = &$obj->$key;
----
Manual Page -- http://www.php.net/manual/en/ref.classobj.php
Edit Note -- http://master.php.net/manage/user-notes.php?action=edit+35349
Delete Note -- http://master.php.net/manage/user-notes.php?action=delete+35349&report=yes
Reject Note -- http://master.php.net/manage/user-notes.php?action=reject+35349&report=yes