如何在PHP中动态添加自定义方法

时间:2014-04-25 13:23:51

标签: php

我有以下课程:

class Sample 
{
    static function Get()
    {
        echo "Get";
    }
}

但我想让自己打电话:

Sample::Put()

然后在PHP中动态添加函数Put() {}Sample类。

这怎么可能?

2 个答案:

答案 0 :(得分:1)

您可以使用magic function __callStatic并添加该功能内的所有逻辑。

class Sample {
  public static function __callStatic($name, $arguments) {
      echo "method called:" . $method;
      return false;
  }
}

答案 1 :(得分:0)

如果您希望新方法实际利用$ this变量,请使用http://php.net/manual/en/closure.bind.php构建一个闭包并将其范围设置为目标对象而不是其出生位置。像这样(未经测试):

class MyTargetClass {
    protected $customMethods = [];

    protected $something = 'testing';

    public function addCustomMethod($name, Callable $closure)
    {
        $this->customMethods[name] = $closure->bindTo($this);
    }

    public function __call($method, $arguments)
    {
        if (array_key_exists($method, $this->customMethods)) {
            $this->customMethods[$method](...$arguments);
        }
        throw new BadMethodCallException();
    }
}

class MyWorkingClass {
    public function someMethod()
    {
        $method = function($field) {return $this->$field};
        $instance = new MyTargetClass();
        $instance->addCustomMethod('get', $method);
        return $instance->get('something');  //should return "testing"
    }
}

有趣的事实:这实际上是Laravel的Macroable特质的作用。