PHP can be a lot of fun. Especially when you find the neat little things you can do with the code. Generally all of these tricks help tackle problems where the solutions have a longer route to accomplish. It’s nice to find the short-cuts.
Anonymous Functions
$this->performHighlight(‘
function getAdder($x) {
return function ($y) use ($x) {
return $x + $y;
};
}
$adder = getAdder(8);
echo $adder(2); // prints “10”
‘, ‘php’, $content);
Anonymous functions, or closures, are found all over JavaScript. These guys allow variable declarations of non-named functions, which you can hide in scope or even attach to objects and arrays.
$this->performHighlight(‘
$array[‘func’] = function(){
echo “hello”;
};
$array[‘func’]();
‘, ‘php’, $content);
Variable Variables
$this->performHighlight(‘
$a = “varz”;
$$a = “foobar”;
echo $varz;
// Output is foobar
‘, ‘php’, $content);
Managing variables using variables within your code, that just makes things so simple. It’s like scripting a script.
$this->performHighlight(‘
for ($i = 1; $i <= 5; $i++) {
${a.$i} = "value";
}
echo "$a1, $a2, $a3, $a4, $a5";
//Output is value, value, value, value, value
', 'php', $content);