This article mainly introduces the use keyword in PHP. if you need it, you can refer to many open-source systems such as the osCommerce framework and find the use keyword in the source code, for example, the osCommerce framework is in index. the PHP file contains the following source code:
use osCommerce\OM\Core\Autoloader;use osCommerce\OM\Core\OSCOM;
In fact, the use keyword of php is introduced from php5.3 or a later version. It serves as an alias for an external reference. This is an important feature of a namespace. it is similar to creating a connection flag for a file or directory in a unix-based file system.
The PHP namespace supports three alias methods (or references ):
1. alias for a class
2. get an alias for an interface
3. get an alias for a namespace
All three methods are completed using the use keyword. The following are examples of the three aliases:
// Example #1 importing/aliasing with the use operator
<?phpnamespacefoo;useMy\Full\ClassnameasAnother;//thisisthesameasuseMy\Full\NSnameasNSnameuseMy\Full\NSname;//importingaglobalclassuseArrayObject;$obj=newnamespace\Another;//instantiatesobjectofclassfoo\Another$obj=newAnother;//instantiatesobjectofclassMy\Full\ClassnameNSname\subns\func();//callsfunctionMy\Full\NSname\subns\func$a=newArrayObject(array(1));//instantiatesobjectofclassArrayObject//withoutthe"useArrayObject"wewouldinstantiateanobjectofclassfoo\ArrayObject?>
Note that for a named name, the full name contains delimiters, such as Foo \ Bar, instead of FooBar, the "\" header of "\ Foo \ Bar" is unnecessary, and it is not recommended to write it like this. The import name must be the full name and has no program association with the current namespace.
PHP can declare multiple statements on the same line, which is equivalent to the above statement.
<?phpuseMy\Full\ClassnameasAnother,My\Full\NSname;$obj=newAnother;//instantiatesobjectofclassMy\Full\ClassnameNSname\subns\func();//callsfunctionMy\Full\NSname\subns\func?>
It is also worth noting that the introduction is executed during compilation, so aliases do not affect dynamic classes, for example:
<?phpuseMy\Full\ClassnameasAnother,My\Full\NSname;$obj=newAnother;//instantiatesobjectofclassMy\Full\Classname$a = 'Another';$obj = New $a; // instantiates object of class Another?>
Here, because the variable $ a is assigned a 'Another ', $ a is located to the Classname during compilation.
For more detailed usage, refer to the php manual or follow the related articles on this site.