PHP - 通过数组在 class 中动态创建方法

PHP - Dynamically create methods in a class by an array

我有一个 class 用未知方法扩展另一个 class。这是 class 的基础:

class SomeClass extends SomeOtherClass {     
}

我还有一个数组,如下所示:

$array = array(
  'aFunctionName' => 'My Value',
  'anotherFunctionName' => 'My other value'
);

它包含一个classname和一个value。问题是我如何在扩展 class 中使用它们,按需动态创建 classes。

结果

这是 PHP 应该如何读取我的数组结果的结果。

class SomeClass extends SomeOtherClass {

  public function aFunctionName() {
    return 'My value';
  }

  public function anotherFunctionName() {
    return 'My other value';
  }
}

是否可以通过这样的数组创建扩展方法?

您可以使用 __call 创建魔术方法,如下所示:

class Foo {

    private $methods;

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

    public function __call($method, $arguments) {
        if(isset($this->methods[$method])) {
            return $this->methods[$method];
        }
    }
}

$array = array(
  'aFunctionName' => 'My Value',
  'anotherFunctionName' => 'My other value'
);

$foo = new Foo($array);
echo $foo->aFunctionName();