如何动态地向php对象添加新方法?
如何“动态”向对象添加新方法?
$me= new stdClass;
$me->doSomething=function ()
 {
    echo 'I\'ve done something';
 };
$me->doSomething();
//Fatal error: Call to undefined method stdClass::doSomething()
如何“动态”向对象添加新方法?
$me= new stdClass;
$me->doSomething=function ()
 {
    echo 'I\'ve done something';
 };
$me->doSomething();
//Fatal error: Call to undefined method stdClass::doSomething()
您可以利用__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();
在 PHP 7 中,您可以使用匿名类,这消除了限制。stdClass
$myObject = new class {
    public function myFunction(){}
};
$myObject->myFunction();
 
				    		 
				    		 
				    		 
				    		