How and where should I use the keyword “use” in php

我是研究僧i 提交于 2019-12-06 00:44:48

In PHP, the keyword use is used in 3 cases:

  1. As class name alias - simply declares short name for a class (must be declared outside of the class definition) (manual: Using namespaces: Aliasing/Importing )
  2. To add a trait to a class (must be declared inside (at the top) of the class definition) (manual: Traits)
  3. In anonymous function definition to pass variables inside the function (manual: Anonymous functions)

use is basically including a class in the file to use it. There are two ways to include a class file in another file. The most general is require or include method. Another method is using composer. Assume this Directory Structure

Project
  |
  |--- Folder A
  |      |
  |      |---UserRegistration.php
  |
  |---Example
         |
         |--TestUserRegistration.php    

In Folder A there is UserRegistartion.php and you want to use the code in TestUserRegistration.php In UserRegistration.php It can be class, trait or Interface

Method 1.

In TestUserRegisteration.php you can include or require file UserRegistartion.php
and use it

Method 2

Using Composer. In UserRegistration.php you define namespace FolderA; as the first line of code. Then write your code as you do. So Now you want to use this file in TestUserRegistration.php you do

include vendor/autoload.php;
use FolderA\UserRegistration;

Which one is better and why?

Method 2 using composer is the best method. In method 1 wherever you want to include UserRegistration you have to find the relative path to UserRegistration file. So lets assume some day you need to change the directory structure your application will break as the relative path you had provided now it does'nt exist.

But in Method 2 you always use the namespace you provided \ The filename instead of where you want to use. So even you change the directory structure you don't have to got all codes and modify the path. It will work as it was. To know more study about how to use namespace and composer.

Sylvester

You can not import class with use keyword. You have to use include/require statement. Even if you use some php auto loader, still autoloader will have to use either include or require internally.

The Purpose of use keyword:

Consider a case where you have two classes with same name; you'll find it strange, but when you are working with big MVC structure, this happens. So if you have two classes with same name, put them in different name spaces. Now consider when your auto loader is loading both classes (does by require), and you are about to use object of class. In this case, the compiler will get confused which class object to load among two. To help the compiler make a decision, you can use the use statement so that it can make a decision which one is going to be used on.

Here refer this How does the keyword 'use' work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!