kramer65
kramer65

Reputation: 53903

How can php-files find namespaces in other php-files?

Coming from Python I'm trying to make sense of the way php uses namespaces. In Python I simply import as follows:

import someModule
from anotherModule import someClass

This works like a charm and exactly like anyone would expect.

In php on the other hand, we've got something like namespaces. As far as I understand I can define a namespace on the top of a myModule.php like this:

namespace myNamespace;

If I'm correct this means that the code in this file can be referred to as (or imported by) the name "myNamespace" in another myWorkingCode.php by doing this:

use myNamespace;

So my question; How does myWorkingCode.php find the myModule.php? Does it need to be in the same folder for this to work or do I need to do anything else?

Upvotes: 2

Views: 138

Answers (1)

Pinoniq
Pinoniq

Reputation: 1385

The use function in php is completly different then the import in python.

Use is there for creating aliases for very long namespaces. example:

use \My\Very\Long\Omg\Its\Sooooo\Long\How\Stupid as veryshort;

Now every class inside that long namespace is available under the namespace veryshort. More info: http://php.net/manual/en/language.namespaces.importing.php

Then, how does php find the correct file? It doesn't. You will have to include it yourself, however if you use a strong naming convention for your files you can use autoloaders with the spl_autoload_register function. A good standard can be found here: http://www.php-fig.org/psr/0/

Upvotes: 2

Related Questions