如何“动态”向对象添加新方法?
$me= new stdClass; $me->doSomething=function () { echo 'I\'ve done something'; }; $me->doSomething(); //Fatal error: Call to undefined method stdClass::doSomething()
您可以利用__call这一点:
__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();