While
reading some code, I came across a pleasantly surprising snippet that a coworker had added, and it went something like this:
Calling functions through variables
function display_output()
{
return 'This is the output text!';
}
$variable = 'display_output';
echo $variable();
Result: $variable() = 'This is the output text!';
With closer inspection, this is a pretty cool feature in PHP. It allows you to dynamically call a function by treating a variable like a function. When parentheses are after the variable name, PHP calls the function whose name equals the variable's value. Ex:
if $foo = 'bar', then doing $foo() will try calling a function named bar(). Sure, the same result can be achieved using IF loops, but in PHP, it's always good to at least know of the alternatives.
Variable variables
$charlie = 'delta';
$delta = 'oscar';
echo $$charlie;
Result: $$charlie = 'oscar';
My coworker,
Oscar, also informed me about "variable variables". These buggers have that extra dollar sign. In the previous example, PHP looks at the value of $charlie, which is 'delta'. It then
returns the value of $delta, which is 'oscar'.
Creating variables dynamically
$when = 'future';
$variable_past = 'Welcome to the past';
${'variable_' . $when} = 'Welcome to the ' . $when;
Result: $variable_future is created, and $variable_future = 'Welcome to the future'
This is helpful for when you need to create numerous variables on the fly, such as within a FOR loop. However, it may end up making more sense to create an associative array, depending on how much data you need stored. Ex:
$container_array['dynamic_name'] = 'some_value'; Again, this all depends on your given situation.