动态创建 PHP 类函数

25

我想在数组上进行迭代,并根据每个项目动态创建函数。 我的伪代码:

$array = array('one', 'two', 'three');

foreach ($array as $item) {
    public function $item() {
        return 'Test'.$item;
    }
}

我该如何着手处理这个问题?


4
我可以问一下,为什么您想要创建这些函数? - Baba
添加过多的动态内容会使程序难以阅读,这等同于难以维护。您能详细说明您拥有什么和您想要得到什么吗? - Sven
1
可能是 Dynamically Create Instance Method in PHP 的重复问题。 - Luís Cruz
1
@Baba和Sven,他提出了一个很好的问题,因为有些函数似乎只有一个单词的区别,但是功能却相同。我们正在复制代码。因此,最好的方法是编写动态代码。 - Abhi
2个回答

33

你可以使用魔术方法__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

示例: http://ideone.com/73mSh

编辑: 如果您正在使用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

示例:http://codepad.viper-7.com/ayGsTu


@NullUserException:感谢您添加“__call()”是一个“魔术方法”的事实。 - gen_Eric
您还可以使用神奇的__get()函数来调用闭包/回调函数,如下所示:请参见Dynamically Create Instance Method in PHP - 如果您真的认为__call()__get()是被要求的,请建议一个现有的问题作为重复。 - hakre
1
你如何在PHP文档块中注释,以便编辑器不警告“不存在的函数”? - Kyslik

4
class 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
@duck 类 方法测试 { public function __call($name, $arguments) { echo "" . "方法: ".$name."\n" . (!empty($arguments) ? "参数: ". implode(', ', $arguments) : "无参数!"). "\n"; } }$obj = new MethodTest;$obj->ExecTest('参数1', '参数2', '其他 ...');$obj->ExecTest(); - quAnton

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接