0
<?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?

3
  • 2
    Can you provide a shorter snippet of code with just the relevant bits please? Commented Nov 20, 2012 at 7:20
  • And format it please. 4-spaces per indent preferably. Commented Nov 20, 2012 at 7:21
  • @robertrocha It works for me. Commented Nov 20, 2012 at 7:29

1 Answer 1

1

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" */
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.