In PHP, if the namespace string is too long, we use use to shorten the namespace accordingly. This is also the role of use in PHP. Below we will introduce to you the usage of use in PHP.
Recommended tutorial: PHP video tutorial
##1. When using the new class, there is no need to use reverse at the front. slash. In addition, when there is no as after use, the shortened namespace defaults to the content after the last backslash.
namespace animal\dog; class Life{ function __construct(){ echo 'dog life!'; } } namespace animal\cat; class Life{ function __construct(){ echo 'cat life!'; } } new Life(); //按照代码执行顺序,这里默认animal\cat这个命名空间 new \animal\dog\Life(); //A use animal\dog; //a new dog\Life(); //B use animal\dog as d; //b new d\Life();
use animal\dog;
use animal\dog as dog;
2. It is not recommended to add the class name after namespace, but it can be added after use.
//name.php namespace animal\dog; class Life{ function __construct(){ echo 'dog life!'; } } namespace animal\cat; class Life{ function __construct(){ echo 'cat life!'; } } use animal\dog\Life as dog; new dog();
Fatal error: Cannot use animal\dog\Life as Life because the name is already in use
//name.php namespace animal\dog; class Life{ function __construct(){ echo 'dog life!'; } } class Dog{ function __construct(){ echo 'dog in dog!'; } } namespace animal\cat; // class Dog{ // function __construct(){ // echo 'dog in cat!'; // } // } class Life{ function __construct(){ echo 'cat life!'; } } use animal\dog; new dog\Dog();
use animal\dog; cat
A brief summary:
use is like a nickname, which can save a lot of trouble both in writing and speaking.The above is the detailed content of What is the usage of use in php. For more information, please follow other related articles on the PHP Chinese website!