我有一个使用未知方法扩展另一个类的类。这是班级的基础:
class SomeClass extends SomeOtherClass {
}
我还有一个如下所示的数组:
$array = array(
'aFunctionName' => 'My Value',
'anotherFunctionName' => 'My other value'
);
它包含classname
和value
。问题是我如何在扩展类中使用它们,动态地按需创建类。
以下是PHP应该如何读取数组结果的结果。
class SomeClass extends SomeOtherClass {
public function aFunctionName() {
return 'My value';
}
public function anotherFunctionName() {
return 'My other value';
}
}
是否可以通过这样的数组创建扩展方法?
答案 0 :(得分:3)
您可以使用__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();