Home >Backend Development >PHP Tutorial >A brief discussion on 3 ways to use the use keyword in PHP

A brief discussion on 3 ways to use the use keyword in PHP

青灯夜游
青灯夜游forward
2021-06-15 18:15:303783browse

This article will introduce to you some common uses of the use keyword in PHP. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

A brief discussion on 3 ways to use the use keyword in PHP

1. Alias ​​reference for namespace

// 命名空间
include 'namespace/file1.php';

use FILE1\objectA;
use FILE1\objectA as objectB;

echo FILE1\CONST_A, PHP_EOL; // 2

$oA = new objectA();
$oA->test(); // FILE1\ObjectA

$oB = new objectB();
$oB->test(); // FILE1\ObjectA

This must be used in daily engineering It will be very common in development. After all, current frameworks all use namespaces. No matter what you do, you cannot do without calling various class dependencies. There will be a large number of use xxx\xxx\xxx; statements above various controller files.

2. Introduction of trait capabilities

// trait
trait A{
    function testTrait(){
        echo 'This is Trait A!', PHP_EOL;
    }
}

class B {
    use A;
}

$b = new B();
$b->testTrait();

Even in the past two years, I still haven’t seen traits used at all. PHP programmers, don't be surprised, this is real. It’s not surprising to think that there are so many projects still using TP3. The trait feature is also a very convenient class function extension mode. In fact, we can think of it as placing this use in the class and it becomes the reference definition of the trait.

3. Anonymous function parameter passing

// 匿名函数传参

$a = 1;
$b = 2;
// function test($fn) use ($a) // arse error: syntax error, unexpected 'use' (T_USE), expecting '{' 
function test($fn)
{
    global $b;
    echo 'test:', $a, '---', $b, PHP_EOL; // test:---2
    $fn(3);
}

test(function ($c) use ($a) {
    echo $a, '---', $b, '---', $c, PHP_EOL;
});
// 1------3

This is a bit interesting. To call external variables in the method, global is required. Here we can also pass variables directly through use(). And this can only be used in anonymous functions.

Test code: https://github.com/zhangyue0503/dev-blog/blob/master/php/202001/source/use keywords in PHP.php

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of A brief discussion on 3 ways to use the use keyword in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete