Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to use the use keyword in PHP

Shulou Source: shulou.com Published: 2022-06-02 09:55:45 09月27日 Update

Today, I will talk to you about how to use the use keyword in PHP. Many people may not know much about it. In order to make you understand better, the editor has summarized the following content for you. I hope you can get something according to this article.

Several uses of use keyword in PHP

After learning and using PHP for so many years, do you know the usage of the keyword use in PHP? Today let's take a look at its three common uses.

1. Alias references / / namespaces for namespaces

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 very common in daily engineering development. After all, the current framework uses namespaces, no matter what can be done without a variety of class-dependent calls, there will be a large number of use xxx\ xxx\ xxx; statements at the top of various controller files.

two。 For the introduction of trait feature capabilities / / trait

Trait A {

Function testTrait () {

Echo 'This is Trait Aids, PHP_EOL

}

}

Class B {

Use A

}

B = new B ()

$b-> testTrait ()

Even in the last two years, you've still seen PHP programmers who haven't used trait at all. Don't be surprised, this is real. It's not surprising to think that so many projects are still using TP3. The trait feature is also a very convenient class function extension mode. In fact, we can think of it as a reference definition of trait when we put this use in the class.

3. Anonymous function passes parameters / / Anonymous function passes parameters

$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

After reading the above, do you have any further understanding of how to use the use keyword in PHP? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.

Tags: Keywords keywords content space functions common features or aliases functions years engineering controllers files more usefulness frameworks patterns knowledge categories Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Apple Shulou Tech Info vpn MariaDB NVidia