Search code examples
phpvariablesanonymous-classvariable-variables

Variable variables, functions and classes


I just recently discovered variable variables in PHP, needless to say, it´s usefulness is immense:

$name = "ABC";
$$name = "DEF";
echo ${"ABC"}; //Gives: DEF

That got me thinking, which brings us to my question:

Since we can have names that´s variable, can´t we also have functions that´s variable? Not 'functions' as in the names of functions, but (more or less) as in:

$func = 'function test() { echo "Success!"; }';
$func(); //If this would work, it would give: Success!

Or, even better, variables classes:

$class = 'class { function test() { echo "Success!"; } }';
$instance = new $class;
$instance->test(); //In a (not-so) perfect world this would give: Success!

Any of this possible?


Solution

  • The only way this would work is using eval.

    $func = "echo 'Success!';";
    eval($func);
    

    You can use variables to call functions as well.

    function foo()
    {
        echo 'Success';
    }
    
    $foo = 'foo';
    $foo();
    

    Keep in mind - you're entering a dangerous area of PHP as this usually only obfuscates your code for any future developers having to maintain your code (including yourself in a few months).