Reputation: 173
PHP offers two syntax for declaring namespaces. You can use a namespace with no braces or with braces as seen below.
Without Braces
namespace foo/bar;
class Any{}
With Braces
namespace foo/bar {
class Any{}
}
Is there a difference in the functionality or behavior of these two ways of using namespaces or do they both work/function the same way?
Upvotes: 16
Views: 4332
Reputation: 2981
How is it possible to set global namespace without brackets?
<?php
declare(encoding='UTF-8');
namespace MyProject {
const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */ }
}
namespace { // global code
session_start();
$a = MyProject\connect();
echo MyProject\Connection::start();
}
?>
just try to write this code in non-brackets style
Upvotes: 0
Reputation: 2491
There are different reasons for each case, there is a good example on the PHP site.
The reason you'd use curly brackets around a namespace is if there are multiple namespaces in the one file or where you need to have global non-namespaced code in the same file as code that is contained within a namespace.
Also if there are multiple namespaces in one file, the non-bracketed syntax is allowed as well.
As per php guidelines this is not recommended and if you can, just keep it to one namespace per file.
Upvotes: 12
Reputation: 173552
In the first variant, you can only use one namespace per file, whereas the second allows for multiple namespaces. They can be used interchangeably and may occur multiple times in a single file to define multiple namespaces. The only reason to use curly braces is in this case:
namespace {
// code is in global scope
}
Other than the above example, a potential downside of having multiple namespaces in a single file is autoloaders that use the directory and file names to resolve classes to load; it's therefore not recommended to have more than one namespace per file, unless you're combining multiple script files into one.
Upvotes: 6
Reputation: 270
I think the first one only includes "Any" class. But the second one includes all classes between curly braces.
Upvotes: -2