можно ли в PHP сделать override метода класса в рантайме?
ну к примеру, что-то вроде
class test
{
public function doSomething()
{
// do something
}
}
$obj = new test;
// здесь начинается код от балды
$pointer = $object->doSomething;
$object->doSomething = function ()
{
pointer ();
// do something else
...
}
$object->doSomething ();
Здравствуйте, ___Avatar___, Вы писали:
Вот решение от одно из проктологов:
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;
Найдено здесь:
http://theserverpages.com/php/manual/en/ref.classobj.php
Здравствуйте, ___Avatar___, Вы писали:
___>можно ли в PHP сделать override метода класса в рантайме?
function f1 () {
echo "f1() <br>\n";
}
class C {
function f($func=NULL) {
if ($func != NULL) {
$func();
return;
}
echo "C->f() <br>\n";
}
}
f1();
$obj = new C;
$obj->f();
$obj->f("f1");