Home > Backend Development > PHP Tutorial > The use of use keyword in php (including code)

The use of use keyword in php (including code)

烟雨青岚
Release: 2023-04-08 19:46:01
forward
3268 people have browsed it

The use of use keyword in php (including code)

Use of use keyword in php

1. use is most commonly used to retrieve classes Aliases can also be used in closure functions. The code is as follows

<?php
function test() {
    $a = &#39;hello&#39;;
    return function ($a)use($a) {
        echo $a . $a;
    };
}
$b = test();
$b(&#39;world&#39;);//结果是hellohello
Copy after login

When running the test function, the test function returns the closure function. The variable in use in the closure function is $ in the test function. a variable, when the closure function is run, "hellohello" is output, which means that the priority of the variables in the function body is: the priority of the variables in use is higher than the priority of the closure function parameters.

2. The parameters in use can also be passed by reference. The code is as follows

Example 1

<?php
function test() {
    $a=18;
    $b="Ly";
    $fun = function($num, $name) use(&$a, &$b) {
        $a = $num;
        $b = $name;
    };
    echo "$b:$a<br/>";
    $fun(30,&#39;wq&#39;);
    echo "$b:$a<br/>";
}
test();
//结果是Ly:18
//结果是wq:30
Copy after login

Example 2

<?php
function index() {
$a = 1;
return function () use(&$a){
echo $a;
$a++;
};
}
$a = index();
$a();
$a();
$a();
$a();
$a();
$a();
//123456
?>
Copy after login

Thank you all for watching, I hope you can improve after learning how to use the use keyword.

Recommended tutorial: "PHP Tutorial"

The above is the detailed content of The use of use keyword in php (including code). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template