4

I am looking for the correct way (if either is correct please let me know) to write namespaces in PHP classes that follow PSR-1 standard. I looked around but didn't see anything specific. Is the correct way to use

Namespace Foo\Bar;

or is it correct to use curly braces such as

Namespace Foo\Bar
{
    // ....
}

If both are correct, is there a particular reason to use one over the other? I realize that this portion might be opinion based though.

ehime
  • 8,025
  • 14
  • 51
  • 110

2 Answers2

3

Form Namespace and Class Names PSR-1 standrad:

Namespaces and classes MUST follow an "autoloading" PSR: [PSR-0, PSR-4].

This means each class is in a file by itself, and is in a namespace of at least one level: a top-level vendor name.

Code written for PHP 5.3 and after MUST use formal namespaces :

Example :

namespace Vendor\Model;

class Foo
{
}

This means that PSR-1 standard recommends the use of your first form, because with the second one (which uses curly braces) you could have more than one namespace in a single file, and this way you're not following the PSR-1 standard for namespaces.

Community
  • 1
  • 1
blackbishop
  • 30,945
  • 11
  • 55
  • 76
2

The bracketed namespace is the recommended method for defining multiple namespaces in a single file.

If you only have one namespace in a file then use the non-bracketed version.

PSR-1 recommends one class per file, so you should probably limit yourself to one namespace per file, too.

Gary Kerr
  • 13,650
  • 4
  • 48
  • 51