Why can I not use a variable to store echo() like I can other functions?
I'm just trying to figure out why I can't do this:
<开发者_Python百科;?php
$a = "echo";
$a("test");
?>
It just returns PHP Fatal error: Call to undefined function echo() in Command line code on line 1
When I can do this:
<?php
$a = "explode";
var_dump($a("|","1|2|3"));
?>
and get the expected result.
Edit: Found a solution to my problem (as inspired by the various answers below). Create an anonymous function inside the variable $a as so:
$a = function($a){echo $a;};
This will only work in PHP 5.3 or greater though.
That's because echo is not a function but a language construct.
Try with print()
instead. That should work fine.
EDIT: As pointed out in the comments print is also a language construct and won't work! Only solution is wrapping echo or print in a user defined function then.
<?php
function output($str){
return print $str;
}
$a = "output";
$a("Lorem Ipsum ...");
?>
Echo isn't a function. It's a language construct that resembles a function but it doesn't return any values. Because of this, it cannot be used in variable functions ($foo = 'echo'; $foo ('hello world');
doesn't work)
You will have to use a different output method from echo (such as print) to do what you want.
Maybe because explode is a function whereas echo is a language construct. Notice there are no brackets when using echo.
look in docs
echo() is not actually a function (it is a language construct), so you are not required to use parentheses with it. echo() (unlike some other language constructs) does not behave like a function, so it cannot always be used in the context of a function. Additionally, if you want to pass more than one parameter to echo(), the parameters must not be enclosed within parentheses.
Because echo is not a function, it is a built in part of PHP. See here: http://www.php.net/manual/en/functions.variable-functions.php
精彩评论