How can I call a PHP function stored as a string from within another PHP function?
I find myself in the situation where I need to call a PHP function stored as a string from another PHP function.
<?php
$phpcodestring = "<?php ec开发者_运维知识库ho 'Hello World!' ?>";
echo $phpcodestring;
?>
How can I get Hello World to render to screen with the above structure?
Back up a few steps - why do you need to do that?
99.9% of the time there is a better way than eval()
.
Or you could use create_function()
which internally uses something like eval()
so isn't much better, especially when you are not defining the function body directly with a string literal so you can be sure there and then there is nothing potentially dangerous.
You can use the infamous eval()
if you thoroughly trust the source of the string. How the hell did you find yourself in that situation?
Sounds like a case of eval().
eval("echo 'Hello world!';");
You should always consider whether it's a good idea or not, though. Security considerations of eval() can be daunting.
G
You can use the eval() function: http://php.net/manual/en/function.eval.php
eval($phpcodestring);
An alternative approach would be to use create_function method, which is a poor implementation of lambda-style functions in PHP.
精彩评论