Skip to content
Advertisement

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

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?

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement