简体   繁体   English

动态创建PHP类函数

[英]Dynamically create PHP class functions

I'd like to iterate over an array and dynamically create functions based on each item. 我想迭代一个数组并根据每个项动态创建函数。 My pseudocode: 我的伪代码:

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

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

How should I go about doing this? 我该怎么做呢?

Instead of "creating" functions, you can use the magic method __call() , so that when you call a "non-existent" function, you can handle it and do the right action. 您可以使用魔术方法__call()代替“创建”函数,这样当您调用“不存在”函数时,您可以处理它并执行正确的操作。

Something like this: 像这样的东西:

class MyClass{
    private $array = array('one', 'two', 'three');

    function __call($func, $params){
        if(in_array($func, $this->array)){
            return 'Test'.$func;
        }
    }
}

Then you can call: 然后你可以打电话:

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

DEMO: http://ideone.com/73mSh 演示: http//ideone.com/73mSh

EDIT : If you are using PHP 5.3+, you actually can do what you are trying to do in your question! 编辑 :如果你使用的是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;
            };
        }
    }
}

This does work, except that you can't call $a->one() directly, you need to save it as a variable . 这确实有效,除了你不能直接调用$a->one() ,你需要将它保存为变量

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

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

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);
}

The above example will output: 上面的例子将输出:

Test: one
Test: two
Test: three

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM