PHP Fun – Anonymous functions and Variable variables

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

$array[‘func’] = function(){
echo “hello”;

‘, ‘php’, $content);

Variable Variables
$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.

for ($i = 1; $i <= 5; $i++) { ${a.$i} = "value"; } echo "$a1, $a2, $a3, $a4, $a5"; //Output is value, value, value, value, value ', 'php', $content);

About Phillihp Harmon

I'm Phillihp. My name can be spelled the same way forwards and backwards, so can my posts... if you wish. I'm out here exploring, learning, and sharing what I find. This is more for fun and personal growth, I aim to be as consistent as possible, so check back daily!
This entry was posted in ***, PHP. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *