我想在数组上进行迭代,并根据每个项目动态创建函数。 我的伪代码:
$array = array('one', 'two', 'three');
foreach ($array as $item) {
public function $item() {
return 'Test'.$item;
}
}
我该如何着手处理这个问题?
我想在数组上进行迭代,并根据每个项目动态创建函数。 我的伪代码:
$array = array('one', 'two', 'three');
foreach ($array as $item) {
public function $item() {
return 'Test'.$item;
}
}
我该如何着手处理这个问题?
你可以使用魔术方法__call()
,而不是“创建”函数,这样当你调用一个“不存在”的函数时,你可以处理它并执行正确的操作。
像这样:
class MyClass{
private $array = array('one', 'two', 'three');
function __call($func, $params){
if(in_array($func, $this->array)){
return 'Test'.$func;
}
}
}
然后您可以调用:
$a = new MyClass;
$a->one(); // Testone
$a->four(); // null
编辑: 如果您正在使用PHP 5.3+,您实际上可以做到您在问题中尝试的事情!
class MyClass{
private $array = array('one', 'two', 'three');
function __construct(){
foreach ($this->array as $item) {
$this->$item = function() use($item){
return 'Test'.$item;
};
}
}
}
这个确实可以工作,但是你不能直接调用$a->one()
,你需要将它保存为变量。
$a = new MyClass;
$x = $a->one;
$x() // Testone
__get()
函数来调用闭包/回调函数,如下所示:请参见Dynamically Create Instance Method in PHP - 如果您真的认为__call()
或__get()
是被要求的,请建议一个现有的问题作为重复。 - hakreclass MethodTest
{
private $_methods = array();
public function __call($name, $arguments)
{
if (array_key_exists($name, $this->_methods)) {
$this->_methods[$name]($arguments);
}
else
{
$this->_methods[$name] = $arguments[0];
}
}
}
$obj = new MethodTest;
$array = array('one', 'two', 'three');
foreach ($array as $item)
{
// Dynamic creation
$obj->$item((function ($a){ echo "Test: ".$a[0]."\n"; }));
// Calling
$obj->$item($item);
}
Test: one
Test: two
Test: three
$a[0]
直接使用 $a
? - duck