Your first closure is experiencing a variable scope issue, $a
does not exist inside the closure. You can fix this by:
- defining
global $a
inside of the closure.
- Use the
use
keyword as in your second example.
- Only available in PHP version
>=
5.3
- Use arguments instead
echo (function($a){ echo $a; })("test");
You should enable error reporting to see why your first closure should not work in the first place
ini_set("display_errors", 1);
error_reporting(-1);
$a = 1;
$b = function(){
echo $a; // Notice: Undefined variable: a in /path/to/script.php on line #
};
$b();
If both hosts are running PHP 5.5, the output should be the same. It might be that 1 is suppressing the notice messages and the other is not. If that's the case, the ini settings you should be looking for are:
error_reporting
display_errors
And as shown above, you can simply change those settings at script run-time by using ini_set()
where error_reporting(-1)
is a simple shortcut to ini_set('error_reporting', E_ALL | E_STRICT)