动态创建PHP类函数 [英] Dynamically create PHP class functions

查看:63
本文介绍了动态创建PHP类函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想遍历数组并根据每个项目动态创建函数.我的伪代码:

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

我应该怎么做?

推荐答案

您可以使用魔术方法 __call() ,这样,当您调用不存在"的函数时,就可以对其进行处理并采取正确的措施.

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.

类似这样的东西:

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+,则实际上您可以可以执行您要解决的问题!

EDIT: If you are using PHP 5.3+, you actually can do what you are trying to do in your question!

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()之外,您需要将其另存为变量.

This does work, except that you can't call $a->one() directly, you need to save it as a variable.

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

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

这篇关于动态创建PHP类函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆