PHP namespaces and use
The use
operator is for giving aliases to names of classes, interfaces or other namespaces. Most use
statements refer to a namespace or class that you'd like to shorten:
use My\Full\Namespace;
is equivalent to:
use My\Full\Namespace as Namespace;
// Namespace\Foo is now shorthand for My\Full\Namespace\Foo
If the use
operator is used with a class or interface name, it has the following uses:
// after this, "new DifferentName();" would instantiate a My\Full\Classname
use My\Full\Classname as DifferentName;
// global class - making "new ArrayObject()" and "new \ArrayObject()" equivalent
use ArrayObject;
The use
operator is not to be confused with autoloading. A class is autoloaded (negating the need for include
) by registering an autoloader (e.g. with spl_autoload_register
). You might want to read PSR-4 to see a suitable autoloader implementation.
Importing a namespace vs. including files in PHP
use
and require_once
are completely different things. use
is not doing any file importing at all. use
is just making your life easier. Instead of writing Full\Path\To\Class
every time, you can do
use Full\Path\To\Class
$bar = new Class();
Your are still responsible to include the right files.
Instead of loading all the files by hand, you could rely on PHP auto class loading.
You can use Composer or Frameworks like Symfony 2 or Zend2 which are handling all the autoloading stuff for you.
Migrating existing code to use autoloading and use
statements instead of include_once
may be very time consuming. There's most likely no search and replace solution.
PHP namespaces and using the \ prefix in declaration
As mentioned in the other answers the namespace
declaration always takes a fully-qualified name and as such a trailing \
would be redundant and is not allowed.
Writing namespace \NYTD\ReadingListBackend { ... }
will lead to a proper parse error.
When using the semicolon notation namespace \NYTD\ReadingListBackend;
on the other hand it is interpreted as namespace\NYTD\ReadingListBackend;
, which is an access to the constant NYTD\ReadingListBackend
(the namespace
keyword here resolves to the currently active namespace, which in your case is the global one).
So your code does not declare any namespace (it is global) and just tries to access a constant. That's why you end up redefining Exception
.
By the way, the reason why the undefined constant access does not throw a fatal error is class hoisting. Your class declaration is evaluated first, so PHP never actually reaches the constant access (even though it comes first in code).
Does use statement order affect functionality in PHP?
When alias namespaces no.
When used in the class body for Traits may affect in certain scenarios related with the use of docblock annotations.
Don't understand php namespace, how can I call function from another class?
ClassNames are considered relative to the current namespace unless they start with a \
This means that inside the MicrosoftAzure\Storage
namespace you can use the relative namespace for class.
If you want to call a class from a different namespace you should call fully-qualified name for it like
$action = \MicrosoftAzure\WhereEver\MicroGrid::GetParameter('action');
or use the name space or unique class with fully-qualified name
use \MicrosoftAzure\WhereEver;
or
use \MicrosoftAzure\WhereEver\MicroGrid;
then:
$action = MicroGrid::GetParameter('action');
Edited to make it clear
namespaces allow us to avoid naming collisions and to alias long
names caused by avoiding naming collisions.
it depends to your autoloader for a simple example I create a new project and make this autoloader in the index.php located at root directory
function __autoload($className){
//if it's a full name with windows style slashes correct the path
$file_name = str_replace('\\', '/', $className);
require_once("vender/src/".$file_name.".php");
}
when I call $date = new \App\Utility\Date();
autoloader will require this file:
verdor/src/App/Utility/Date.php
and in Date.php
I used this name space namespace App\Utility;
When should I use namespaces in PHP?
The main objective of namespaces is to prevent name collisions, more over they are used to group classes, methods. As you mentioned there are a lot of classes within a Laravel project so namespaces would have to be used to prevent collisions which will happen in big projects.
You can 'nest' namespaces as you desire, this is usually paired to your folder structure and is relevant if you are using PSR-4 autoloading standard which laravel uses.
For example you may a User class (Model) and a User class (Repository). Putting them under
namespace Model
and
namespace Repository
will make a lot of sense to you, PHP and the autoloader.
Related Topics
How to Access MySQL Result Set Data With a Foreach Loop
In PHP, What Does "≪≪≪" Represent
How to Generate a Screenshot of a Webpage Using a Server-Side Script
Serializing and Submitting a Form With Jquery and PHP
Why I'M Getting 500 Error When Using File_Get_Contents(), But Works in a Browser
How to Execute PHP That Is Stored in a MySQL Database
A Problem Occurred Somewhere in the Ssl/Tls Handshake
PHP Header Redirect Not Working
Pdo Prepared Statements With Wildcards
File_Get_Contents(): PHP_Network_Getaddresses: Getaddrinfo Failed: Name or Service Not Known
Resetting Array Pointer in Pdo Results
I Cannot Get My Login Form to Connect Interact Properly With MySQL Database
Insert - Number of Bind Variables Doesn't Match Number of Fields in Prepared Statement