Reputation: 10380
<?php
namespace Top
{
$a = "Robert";
$b = "Richard";
$c = "Maurice";
function get_a()
{
global $a;
return $a;
}
function get_b()
{
global $b;
return $b;
}
function get_c()
{
global $c;
return $c;
}
echo namespace\Middle\get_a();
echo namespace\Middle\Bottom\get_c();
echo namespace\get_b();
}
namespace Top\Middle
{
$a = "Dauraun";
$b = "Khalid ";
$c = "Humberto";
function get_a()
{
global $a;
return $a;
}
function get_b()
{
global $b;
return $b;
}
function get_c()
{
global $c;
return $c;
}
}
namespace Top\Middle\Bottom
{
$a = "Terry";
$b = "Jesse";
$c = "Chris";
function get_a()
{
global $a;
return $a;
}
function get_b()
{
global $b;
return $b;
}
function get_c()
{
global $c;
return $c;
}
}
?>
So in the above code snippet I am trying to display the correct variable content using a function using the global keyword with the corresponding namespace yet, the desired result is not happening. The returned variable content is that of the namespace where the echo statement is used and not from the specified namespace. The output being 'RobertMauriceRichard.' Can someone please explain? Perhaps it's a misunderstanding on my part of the 'global' keyword inside a function that is in a namespace?
Upvotes: 0
Views: 360
Reputation: 10070
Because only 4 types of code are affected by namespace: classes, interfaces, functions, constants.
So your $a
, $b
, $c
and echo
statement are available - and actually the same - across the whole file.
By the time you call namespace\Middle\get_a();
, $a
is still "Robert", so "Robert" is returned.
Try to put the echo
group into different namespace, and you'll observe different result:
namespace Top\Middle
{
/*...*/
echo \Top\Middle\get_a();
echo \Top\Middle\Bottom\get_c();
echo \Top\get_b();
}
/* outputs "DauraunHumbertoKhalid" */
namespace Top\Middle\Bottom
{
/*...*/
echo \Top\Middle\get_a();
echo \Top\Middle\Bottom\get_c();
echo \Top\get_b();
}
/* outputs "TerryChrisJesse" */
Upvotes: 1