如何将新方法“动态”添加到对象中?
$me= new stdClass;
$me->doSomething=function ()
{
echo 'I\'ve done something';
};
$me->doSomething();
//Fatal error: Call to undefined method stdClass::doSomething()
发布于 2010-05-30 17:00:05
您可以利用__call
实现以下功能:
class Foo
{
public function __call($method, $args)
{
if (isset($this->$method)) {
$func = $this->$method;
return call_user_func_array($func, $args);
}
}
}
$foo = new Foo();
$foo->bar = function () { echo "Hello, this function is added at runtime"; };
$foo->bar();
发布于 2016-03-05 02:01:19
在PHP7中,您可以使用匿名类,这消除了stdClass
的限制。
$myObject = new class {
public function myFunction(){}
};
$myObject->myFunction();
发布于 2014-05-01 07:11:09
简单地使用__call来允许在运行时添加新方法有一个主要缺点,那就是这些方法不能使用$this实例引用。一切都很好,直到添加的方法没有在代码中使用$this。
class AnObj extends stdClass
{
public function __call($closure, $args)
{
return call_user_func_array($this->{$closure}, $args);
}
}
$a=new AnObj();
$a->color = "red";
$a->sayhello = function(){ echo "hello!";};
$a->printmycolor = function(){ echo $this->color;};
$a->sayhello();//output: "hello!"
$a->printmycolor();//ERROR: Undefined variable $this
为了解决这个问题,你可以这样重写模式
class AnObj extends stdClass
{
public function __call($closure, $args)
{
return call_user_func_array($this->{$closure}->bindTo($this),$args);
}
public function __toString()
{
return call_user_func($this->{"__toString"}->bindTo($this));
}
}
通过这种方式,您可以添加可以使用实例引用的新方法
$a=new AnObj();
$a->color="red";
$a->sayhello = function(){ echo "hello!";};
$a->printmycolor = function(){ echo $this->color;};
$a->sayhello();//output: "hello!"
$a->printmycolor();//output: "red"
https://stackoverflow.com/questions/2938004
复制相似问题