Is it required to include the namespace file?

namespaces, php

Solution

The answer to your question is "yes and no".

Indeed the code implementing class `Person` has to be included, otherwise the class is not defined and cannot be used. Where should the definition come from, when the code is not included? The php interpreter cannot guess the classes implementation. That is the same in all programming languages, by the way.

However there is something called Autoloading in php. It allows to automatically include certain files. The mechanism is based on a mapping of class names to file names. So in the end it boils down to php searching through a folder structure to find a file whos name suggests that it implements a class currently required in the code it executes.

But don't get this wrong: that still means the file has to be included. The only difference is: the including is done automatically, so without you specifying an explicit `include` or `require` statement.

Problem

This is what I have at hand: ``` //Person.php namespace Entity; class Person{ } ``` User file: ``` //User.php use Entity\Person; $person = new Person; ``` Here, it fails if I don't include the `Person.php` file. If I include it, the everything works fine. Do I absolutely require to include the file even when using namespaces? If at all we need to include/require files, then how can namespaces be effectively used? Also, can we maintain folder structure by nesting namespaces?

Original source

Related problems