收录日期:2019/08/19 20:43:44 时间:2014-02-09 18:33:31 标签:php,function

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.

There are two possible issues, and you should address them both:

  1. That feature only works in PHP 5.3, to the best of my recollection. That's the newest major version, so you should ensure that you're using it. It's very likely that you're not.
  2. echo is not a function, but rather a PHP language construct. You'll need to write a wrapper function that echoes what was passed to it.

This works:

$v = "printf";
$v('foo');