Reputation: 739
Somehow, the following results in NULL. Why is this the case? I find it important to know, because the use
statements does not support variable variables.
function a() {
$a = "a";
$aa = function() {
global $a;
var_dump($a);
};
$aa();
}
a();
Upvotes: 0
Views: 192
Reputation: 122489
global $a
access a global variable called $a
. It is not the local variable in the function a
. Since you have never initialized a global variable called $a
, it is NULL.
In order for local variables to be usable inside an anonymous function, they must be captured using a use
clause. Local variables can either be captured by value or by reference.
If you want to capture by value (which means the value of the local variable $a
is copied into the closure at the time it's defined):
function a() {
$a = "a";
$aa = function() use ($a) {
var_dump($a);
};
$aa();
}
a();
If you want to capture by reference (which means inside the closure it directly references the variable $a
):
function a() {
$a = "a";
$aa = function() use (&$a) {
var_dump($a);
};
$aa();
}
a();
In this case both would be the same. But if you modified the variable after the closure was created, and before it is run, it would give a different result (the capture by value would still have the previous value).
Upvotes: 0
Reputation: 9920
Variable $t
is the variable variable you can access with $$a
. Note that inside the function a()
, $t
is never used, so should be what you want.
$t = 3;
$a = 't';
function a()
{
global $a, $$a;
$x = $$a;
$b = function() use ($x) {
echo $x;
};
$b();
}
a();
The code prints 3
.
Upvotes: 0
Reputation: 489
Maybe you can make a reference to the variable variables.
function a() {
$a = "b";
$b = "variable";
$ref = &$$a;
$aa = function() use ($ref) {
var_dump($ref);
};
$aa();
}
a();
which outputs: string(8) "variable"
Upvotes: 0
Reputation: 27565
The value is NULL
because there is no global with name $a
.
The following would print "global":
$a = "global"; // global variable initialization
function a() {
$a = "a";
$aa = function() {
global $a;
var_dump($a);
};
$aa();
}
a();
Upvotes: 1
Reputation: 360
You can write this :
function a() {
$a = "a";
function b() {
global $a;
var_dump($a);
};
$aa = "b";
$aa();
}
a();
Upvotes: 0