首页 > 解决方案 > 如何动态地将方法添加到类中?

问题描述

我知道我可以在运行时向 PHP 类动态添加属性(参见下面的示例)。
但是我找不到在运行时向类添加方法的方法。
到目前为止我已经尝试过:

    class Test {  

            public $name;  

            public function __construct($name){  
                $this->name=$name;  
            }  

            public function addProperty($name,$value){  
                $this->$name=$value;  
            }  

            public function addMethod($name, $value) {  
                 $this->$name=$value;  
            }  

    }  


    $t=new Test("Morris");  
    echo $t->name .'<br>'; // => "Morris"  
    echo $t->firstname .'<br>'; // as expected => "Notice: Undefined property: Test::$firstname"  

    $t->addProperty("firstname","John"); // dynamically add new property  
    echo $t->firstname .'<br>'; // => "John" (property has definitely been added).

    $f=function($i){return $i*$i;};  
    echo $f(7); // ==> 49  

    $t->addMethod("square",$f); // trying to dynamically add a new method  
    echo $t->square(4); // expected: 46, but..... => "Fatal error: Call to undefined method Test::square()"  

这行不通。
还有什么我应该做的addMethod()吗?
或者一些应该被覆盖的魔法类方法?
有可能吗?

标签: php

解决方案


请找到以下代码

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();

推荐阅读