Tramaine Darby

Tramaine Darby

Raleigh NC 27675
Tramaine Darby
917-300-9122 tramainedarby@gmail.com

PHP Anonymous functions

February 18, 2015, by tdarby, category PHP

Learned something new today!

In php you can create an anonymous function  that will just execute inline:

<?php
$greetings = function($name)
{
printf("Wassup %s\r\n", $name);
};

These function will  make the functionality cleaner when used as callbacks or simple variable assignment.  It creates a closure, so the variables will not bleed out.  If you want to inherit variables from the calling scope, add the “use” directive:

<?php

$message = 'This is awesome';

$logger = function () use ($message) {
var_dump($message);
};

The gotcha here is that the variables are inherited as they are when the function is created, not when it is executed.

http://php.net/manual/en/functions.anonymous.php

 

So, what do you think ?