I have a file that require()'s a namespace, as such:
<?php
require_once('Beer.php'); // This file contains the Beer namespace
$foo = new Beer\Carlsburg();
?>
I would like to put the Beer namespace directly in the same file, like this (unworking) example:
<?php
namespace Beer {
class Carlsburg {}
}
$foo = new Beer\Carlsburg();
?>
However, the PHP interpreter complains that No code may exist outside of namespace
. I can therefore wrap $foo
declaration in a namespace, but then I must also wrap Beer in that namespace to access it! Here is a working example of what I am trying to avoid:
<?php
namespace Main\Beer {
class Carlsburg {}
}
namespace Main {
$foo = new Beer\Carlsburg();
}
?>
Is there any way to include the code for the Beer
namespace in the file, yet not wrap the $foo
declaration in its own namespace (leave it in the global namespace)?
Thanks.
Defining multiple namespaces in the same file ¶ Multiple namespaces may also be declared in the same file. There are two allowed syntaxes. This syntax is not recommended for combining namespaces into a single file. Instead it is recommended to use the alternate bracketed syntax.
Global space ¶ Without any namespace definition, all class and function definitions are placed into the global space - as it was in PHP before namespaces were supported. Prefixing a name with \ will specify that the name is required from the global space even in the context of the namespace.
You can have the same name defined in two different namespaces, but if that is true, then you can only use one of those namespaces at a time. However, this does not mean you cannot use the two namespace in the same program. You can use them each at different times in the same program.
You can access the global namespace if you use brackets like this: namespace My\Space { function myScopedFunction() { .. } } namespace { function myGlobalFunction() { .. } }
You should use the global namespace :
<?php
namespace Beer {
class Carlsburg {}
}
namespace { // global code
$foo = new Beer\Carlsburg();
}
?>
See here -> http://php.net/manual/en/language.namespaces.definitionmultiple.php
Try this
namespace Beer {
class Carlsburg {}
}
//global scope
namespace {
$foo = new Beer\Carlsburg();
}
As per example #3 in Defining multiple namespaces in the same file
Try placing a backslash before the namespace name:
$beer = new \Beer\Carlsberg();
The initial backslash is translated to "global namespace". If you do not put the leading backslash, the class name is translated to the current namespace.
Just write it, it has no "name":
<?php
namespace Main\Beer {
class Carlsburg {}
}
namespace {
use Main\Beer;
$foo = new Beer\Carlsburg();
}
?>
Demo and see Defining multiple namespaces in the same fileDocs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With