Home > Article > Backend Development > What is the usage of use in php
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();Comparing lines A and B, please note: After using use, there is no backslash at the front of the new class. When use is not used, there is a backslash at the beginning of the namespace By comparing lines a and b, we can understand: When there is no as after use, it is shortened The namespace defaults to what follows the last backslash. As above:
use animal\dog;is equivalent to
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();As shown above, adding the class name after use is equivalent to changing the name of the class: from Life to dog. If you don’t use as dog above, you will get an error:
Fatal error: Cannot use animal\dog\Life as Life because the name is already in useBecause there is also a Life class with the same name under cat.
//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();As above, using
use animal\dog; catThrough the above code, the purpose of using use (shortening the namespace name) is obvious.
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!