PHP Namespaces Declaring namespaces

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

A namespace declaration can look as follows:

  • namespace MyProject; - Declare the namespace MyProject
  • namespace MyProject\Security\Cryptography; - Declare a nested namespace
  • namespace MyProject { ... } - Declare a namespace with enclosing brackets.

It is recommended to only declare a single namespace per file, even though you can declare as many as you like in a single file:

namespace First {
    class A { ... }; // Define class A in the namespace First.
}

namespace Second {
    class B { ... }; // Define class B in the namespace Second.
}

namespace {
    class C { ... }; // Define class C in the root namespace.
}

Every time you declare a namespace, classes you define after that will belong to that namespace:

namespace MyProject\Shapes;

class Rectangle { ... }
class Square { ... }
class Circle { ... }

A namespace declaration can be used multiple times in different files. The example above defined three classes in the MyProject\Shapes namespace in a single file. Preferably this would be split up into three files, each starting with namespace MyProject\Shapes;. This is explained in more detail in the PSR-4 standard example.



Got any PHP Question?