PHP Namespace Syntax: What is the Difference with Braces vs. without Braces?

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.


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.

Tags:

Php

Namespaces