I'm new to PHP
and was learning about PHP
functions from w3schools. It said "PHP allows a function call to be made when the function name is in a variable"
This program worked
<?php
$v = "var_dump";
$v('foo');
?>
But this program did not work:
<?php
$v = "echo";
$v('foo');
?>
But if I do echo('foo');
it works.
What am I doing wrong?
This feature of PHP
is called Variable functions.
The issue here is with echo
which is not really a function but a language construct and variable functions can only be used with functions. In your first example var_dump
was a function and it worked fine.
From PHP doc for Variable functions:
Variable functions won't work with language constructs such as echo(), print(), unset(), isset(), empty(), include(), require() and the like. Utilize wrapper functions to make use of any of these constructs as variable functions.
You can make use of printf
function in place of echo
as:
$e = "printf"; // printf is a function not a language construct.
$e('foo');
or you can write a wrapper function for echo
as:
$e = "echo_wrapper";
$e('foo');
function echo_wrapper($input) { // wrapper function that uses echo.
echo $input;
}
echo
is not a function! You can use printf
which is a function and it can be used to print out something.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With