开发者

Generating lambda function from eval()

I have few helpers - I want to redclare each helper's method as a lambda anonymous function.

I'm trying to do it by getting the helpers methods, and then doing an eval function, but it wont work, im getting parse error..

My current code:

            foreach($this->helpers as $helper)
            {
                include(master_path . 'helpers/'.$helper.'Helper.php');

                $helperClass = new applicationHelper();
                $meth开发者_开发问答ods = get_class_methods($helperClass);
                foreach($methods as $method )
                {

                    eval ( "\$$method = function (\$text) {
                        \$helperClass->$method(\$text);
                    }");

                }
             }

Due to efficiency fears - I'd like a better solution if you know it, thanks! Thanks Guys!


That should work:

foreach($methods as $method )
{
    $$method = function($text) use ($method, $helperClass) {
        return $helperClass->$method($text);
    }
}

But still dont know why are you doing that.

EDIT PHP 5.3.x needed -> look here Anonymous funcions


foreach ($this->helpers as $helper) {
    include(master_path . 'helpers/'.$helper.'Helper.php');

    $helperClass = new applicationHelper();
    foreach (get_class_methods($helperClass) as $method) {
        $$method = function($text) use($helperClass, $method) {
            $helperClass->$method($text);
        };
    }
}

That get's rid of the slow eval.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜