tags:

views:

189

answers:

5

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?

+15  A: 

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;
}
codaddict
@Shiki: `print()` would also not work. You can use `printf()`.
codaddict
you're right. oops
Shiki
Also, if you really need to do this (can't think of a situation in which you would) you can wrap the echo in a functionfunction echoIt($string) { echo $string;}$v = 'echoIt';$v('foo');
David
+1  A: 

echo is not a function! You can use printf which is a function and it can be used to print out something.

Salman A
No need to shout! Although I do agree the fact is non-obvious and poor language design.
erisco
A: 

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.
Jeremy DeGroot
Variable functions were introduced long before PHP 5.3. I do not know the exact version number though.
erisco
A: 

Thanks you all for the answers.

oncode
oncode: do not enter a new answer for this. This should be in a comment to your original question.
Matt Ellen
he's new... please don't downvote... welcome newcomers :)
Alec Smart
A: 

This works:

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