是否可以动态地向/扩展类添加代码?

Sav*_*net 4 php

我想为我的代码编写一种"插件/模块"系统,如果我可以在定义后将其"添加"到类中,它会更容易.

例如,像这样:

class foo {
  public function a() {
     return 'b';
  }
}
Run Code Online (Sandbox Code Playgroud)

这是班级.现在我想在定义后添加另一个函数/变量/ const.

我意识到这可能是不可能的,但我需要确认.

Ger*_*umm 6

不,您无法在运行时向已定义的类添加方法.

但是您可以使用__call/__callStatic魔术方法创建类似的功能.

Class Extendable  {
    private $handlers = array();
    public function registerHandler($handler) {
        $this->handlers[] = $handler;
    }

    public function __call($method, $arguments) {
        foreach ($this->handlers as $handler) {
            if (method_exists($handler, $method)) {
                return call_user_func_array(
                    array($handler, $method),
                    $arguments
                );
            }
        }
    }
}

Class myclass extends Extendable {
    public function foo() {
        echo 'foo';
    }
}

CLass myclass2 {
    public function bar() {
        echo 'bar';
    }
}

$myclass = new myclass();
$myclass->registerHandler(new myclass2());

$myclass->foo(); // prints 'foo'
echo "\n";

$myclass->bar(); // prints 'bar'
echo "\n";
Run Code Online (Sandbox Code Playgroud)

这个解决方案非常有限,但它可能适合您