Question

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?

Was it helpful?

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).

OTHER TIPS

needless to say, it´s usefulness is immense

You cannot be more wrong.
There is absolutely nothing great about variable variables. You'd better discovered arrays

PHP has variable function names as well and it's a bit more usable but still it makes reading your code a torture. So, better to avoid them as well.

Remember the fate of most-known write-only language. PHP ate it in one gulp, only because of PHP's readability. Do not try to make Perl out of PHP. Writing code is leisure but hunting down errors in it - is a REAL job. Don't make your job harder.

Do not write obscure and puzzled code.
Write straight and clean code.
You'd make a huge favor to yourself and other people who happen to work with it.

don't know about your third example, but your second one should almost work (assuming you're using php 5.3 or higher ;) ). just leave yout the quotes and the functions name:

$func = function() { echo "Success!"; };
$func(); //should give: Success!

search for "anonymous function" or, to read more about this, just take a look at the documentation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top