October 28, 2012

Why couldn't I call eval() in this way?

Question by warl0ck

Why is the following code fails to compile:

<?php
  $str = "echo "ok"";
  $func = "eval";
  $func ($str);
?>

And php tells me eval was undefined.

Answer by Boann

In PHP, eval is a “language construct”, not a function. (Notice It turns keyword-color in syntax highlighting editors.) Language constructs cannot be called using the variable function syntax $func() or used with other function-specific things like is_callable().

From http://www.php.net/manual/en/functions.variable-functions.php:

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.

Answer by Starx

eval() cannot be called using a variable function. If you don’t understand what a variable function is? look at the following part of your code

  $func = "eval";
  $func ($str); //Here $func becomes eval upon execution making it a variable function

If you look at the manual reference, its clearly noted

Note: Because this is a language construct and not a function, it cannot be called using variable functions.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!