动态创建PHP类函数

时间:2012-10-12 22:39:51

标签: php

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

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

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

我该怎么做呢?

3 个答案:

答案 0 :(得分:28)

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

DEMO: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(),需要save it as a variable

$a = new MyClass;
$x = $a->one;
$x() // Testone

DEMO:http://codepad.viper-7.com/ayGsTu

答案 1 :(得分:3)

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

答案 2 :(得分:-2)

不确定您的情况,您可以使用create_function创建匿名函数。