Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this PHP program not work?

Tags:

function

php

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?

like image 390
oncode Avatar asked May 12 '10 12:05

oncode


2 Answers

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;
}
like image 197
codaddict Avatar answered Nov 19 '22 07:11

codaddict


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

like image 1
Salman A Avatar answered Nov 19 '22 08:11

Salman A