Create dynamic php function and run it later - Save it to a variable

旧时模样 提交于 2020-01-13 19:46:33

问题


Im trying to make a function to run it later.

In php 5.3.2-1 it works fine. But in 5.1.6 it doesn't.

The code is:

$func = function(){                                                             
  echo "Hello!";                                                                
};                                                                              

echo "Before Hello";                                                            
$func();   

Does anyone knows how to emulate this in 5.1.6?

Thanks.

Eduardo


回答1:


Anonymous functions are available since PHP 5.3. You cannot use them in older versions. Take a look at the docs.




回答2:


$func = create_function('','echo "Hello!";');

echo "Before Hello";
$func();

to be able to "assign a function to a variable", while not delving into eval-ish code:

function my_not_so_anonymous_function1()
{
    echo "Hello!";
}
$func = 'my_not_so_anonymous_function1';

echo "Before Hello";
$func();


来源:https://stackoverflow.com/questions/4584419/create-dynamic-php-function-and-run-it-later-save-it-to-a-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!