【问题标题】:PHP - Dynamically create methods in a class by an array [duplicate]PHP - 通过数组在类中动态创建方法[重复]
【发布时间】:2017-08-06 08:36:36
【问题描述】:

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

class SomeClass extends SomeOtherClass {     
}

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

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

它包含classnamevalue。问题是我如何在扩展类中使用它们,按需动态创建类。

结果

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

class SomeClass extends SomeOtherClass {

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

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

这样的数组可以创建扩展方法吗?

【问题讨论】:

标签: php arrays class oop extends


【解决方案1】:

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2012-05-27
  • 1970-01-01
  • 2014-10-06
  • 1970-01-01
  • 2015-11-15
  • 2020-12-05
  • 2011-03-14
  • 1970-01-01
相关资源
最近更新 更多