如何动态地向php对象添加新方法?

2022-08-30 07:28:23

如何“动态”向对象添加新方法?

$me= new stdClass;
$me->doSomething=function ()
 {
    echo 'I\'ve done something';
 };
$me->doSomething();

//Fatal error: Call to undefined method stdClass::doSomething()

答案 1

您可以利用__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();

答案 2

在 PHP 7 中,您可以使用匿名类,这消除了限制。stdClass

$myObject = new class {
    public function myFunction(){}
};

$myObject->myFunction();

PHP RFC: 匿名类


推荐