Namespaces and autoloading

3rd Mar 19

As your project gets bigger, you will have to include a greater number of files you need to include.  Php provides a way you can include classes automatically and namespaces help you structure your website better.


You can add a namespace to the top of your file.  To instantiate the class you need to add the namespace before the class with backslashes.  It can be thought of as like a virtual file system.  It is best practice to match namespaces with the actual file structure.  So in the below example the Bird.php file would be in the Natalie directory.  This naming convention is known as PRS-4.  

namespace Natalie;

class Bird { ...


$bird = new \Natalie\Bird()


By using PSR-4 you can easily convert namespaces into directories.  

I have recently completed my apprenticeship.  I am currently building the API to a React JS site using Firebase.