簡體   English   中英

動態創建PHP類函數

[英]Dynamically create PHP class functions

我想迭代一個數組並根據每個項動態創建函數。 我的偽代碼:

$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

演示: 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

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

在您的情況下不確定用法,您可以使用create_function創建匿名函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM