Sure you can do globals, but of PHP 5.3.0+ has anonymous functions, so you can also do closures:
<?php
function a(){
$a = 1;
echo "First: $a, ";
++$a;
// This is a closure. It can gain access to the variables of a() with the
// use option.
$b = function() use ($a) {
echo "second: $a";
};
$b();
};
a(); // Outputs: First: 1, second: 2
?>
or probably more useful:
<?php
function a(){
$a = 1;
echo "First: $a, ";
++$a;
$b = function() use ($a) {
echo "second: $a";
};
return $b;
};
$fun = a(); // $fun is now $b & $b has access to $a!
$fun();
// Outputs: First: 1, second: 2
?>
From the docs:
Closures may also inherit variables from the parent scope. Any such variables must be declared in the function header. Inheriting variables from the parent scope is not the same as using global variables. Global variables exist in the global scope, which is the same no matter what function is executing. The parent scope of a closure is the function in which the closure was declared (not necessarily the function it was called from).