Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it required to include the namespace file?

Tags:

namespaces

php

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?

like image 962
Rutwick Gangurde Avatar asked May 30 '14 13:05

Rutwick Gangurde


People also ask

What is #include namespace?

A namespace is a declarative region that provides a scope to the identifiers (the names of types, functions, variables, etc) inside it. Namespaces are used to organize code into logical groups and to prevent name collisions that can occur especially when your code base includes multiple libraries.

What is the purpose of namespace in PHP?

In the PHP world, namespaces are designed to solve two problems that authors of libraries and applications encounter when creating re-usable code elements such as classes or functions: Name collisions between code you create, and internal PHP classes/functions/constants or third-party classes/functions/constants.

What are the benefits of namespace?

Advantages of namespace In one program, namespace can help define different scopes to provide scope to different identifiers declared within them. By using namespace - the same variable names may be reused in a different program.


2 Answers

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.

like image 108
arkascha Avatar answered Sep 16 '22 16:09

arkascha


Yes, you need to include every file. A very good example can be found here on effective usage of namespaces.

like image 28
gnagy Avatar answered Sep 17 '22 16:09

gnagy