PHP: Namespaces
Namespacing does for functions and classes what scope does for variables. It allows you to use the same function or class name in different parts of the same program without causing a name collision.
In simple terms, think of a namespace as a person’s surname. If there are two people named “John” you can use their surnames to tell them apart.
Then in another file we call it like this:
Another thing to watch out for is using classes in a different namespace. For example, most built-in PHP classes are located in the global top level namespace. For example, if you tried using the following code.
PHP would yell at you with the following error message
PHP assumed we wanted a class named My\SpecialNamespace\DomDocument. The same thing that lets us say new MyClass also means we need to be explicit with our other classes.
We have two options here:
1. Use leading slash, this tells PHP to use global
class DomDocument
;
2.Import that class with use
. Then you can use DomDocument
without leading slash.
This will work with any class, not just built-in PHP classes. Consider the Some\Other\Class\Thing class below.