从 eval() 生成 lambda 函数

发布于 2024-10-14 23:51:36 字数 684 浏览 1 评论 0原文

我有几个助手 - 我想将每个助手的方法重新声明为 lambda 匿名函数。

我试图通过获取辅助方法,然后执行 eval 函数来实现此目的,但它不起作用,我收到解析错误。

我当前的代码:

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

                $helperClass = new applicationHelper();
                $methods = get_class_methods($helperClass);
                foreach($methods as $method )
                {

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

                }
             }

由于效率担忧 - 如果您知道,我想要一个更好的解决方案它,谢谢! 谢谢你们!

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();
                $methods = 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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

夜巴黎 2024-10-21 23:51:36

这应该可行:

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

但仍然不知道你为什么这样做。

编辑
需要 PHP 5.3.x ->看这里匿名函数

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

深者入戏 2024-10-21 23:51:36
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);
        };
    }
}

这样就摆脱了缓慢的eval

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文