1

I've never really worked with PHP namespacing before and I was reading up on how to use it on the PHP website, including how to include namespace code and non-nonspace (global code) in the one file.

Source: http://www.php.net/manual/en/language.namespaces.definitionmultiple.php

I then tried the below for testing:

namespace {

    $bar = 123;

}

namespace moo {

    $bar = 400;

}

namespace {

    echo $bar . "<br>\n";
    //echo moo\$bar . "<br>\n";    

}

However what I got back was unexpected..

The output of the above is:

400

Shouldn't it be 123 since I am not referencing the moo namespace? Additionally, if I uncomment the next line I get a PHP syntax error.

What am I doing wrong?

Brett
  • 19,449
  • 54
  • 157
  • 290
  • That form of `{}` after namespaces is new to me, I thought it was just a command at the beginning of a PHP file and I think there is something in the documentation that says variables are always global:http://www.php.net/manual/en/language.namespaces.definition.php – Jason Sperske Jan 30 '14 at 17:15
  • @JasonSperske Well it said you have to use brackets if you want to use global and namespace code in the same file. My bad about the variable though, which is a pain. :( – Brett Jan 30 '14 at 17:18
  • "It is strongly discouraged as a coding practice to combine multiple namespaces into the same file." - From the php.net page you referenced. What are you trying to accomplish here? This is not how traditional namespacing is used. – Mitch Jan 30 '14 at 17:19
  • @mitch I'm trying to build implement a SSO (single-sign on) with Invision Power Board, but I need to include a bunch of my own code and files inside one of their files but my database $object seems to be getting wiped or something. – Brett Jan 30 '14 at 17:24

1 Answers1

2

Here Can PHP namespaces contain variables? is your answer: "variables will always exist in the global scope. They are never bound to namespaces."

Community
  • 1
  • 1
S Korolev
  • 346
  • 1
  • 6