Search code examples
phpevalphp-5.3

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


Solution

  • 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