设为首页 - 加入收藏 ASP站长网(Aspzz.Cn)- 科技、建站、经验、云计算、5G、大数据,站长网!
热搜: 创业者 手机 数据
当前位置: 首页 > 站长学院 > PHP教程 > 正文

use关键字在php里的使用含代码

发布时间:2022-06-24 12:55 所属栏目:121 来源:互联网
导读:use关键字在php中的使用 1、use最常用在给类取别名,还可以用在闭包函数中,代码如下: ?php function test() { $a = hello; return function ($a)use($a) { echo $a . $a; }; } $b = test(); $b(world);//结果是hellohello 当运行test函数,test函数返回闭
  use关键字在php中的使用
 
  1、use最常用在给类取别名,还可以用在闭包函数中,代码如下:
 
  <?php
  
  function test() {
  
      $a = 'hello';
  
      return function ($a)use($a) {
  
          echo $a . $a;
  
      };
  
  }
  
  $b = test();
  
  $b('world');//结果是hellohello
  当运行test函数,test函数返回闭包函数,闭包函数中的use中的变量为test函数中的$a变量,当运行闭包函数后,输出“hellohello”,由此说明函数体中的变量的优先级是:use中的变量的优先级比闭包函数参数中的优先级要高。
 
  2、use中的参数也可以使用引用传递的,代码如下
 
  示例一:
 
  <?php
  
  function test() {
  
      $a=18;
  
      $b="Ly";
  
      $fun = function($num, $name) use(&$a, &$b) {
  
          $a = $num;
  
          $b = $name;
  
      };
  
      echo "$b:$a<br/>";
  
      $fun(30,'wq');
  
      echo "$b:$a<br/>";
  
  }
  
  test();
  
  //结果是Ly:18
  
  //结果是wq:30
  示例二
 
  <?php
  
  function index() {
  
  $a = 1;
  
  return function () use(&$a){
  
  echo $a;
  
  $a++;
  
  };
  
  }
  
  $a = index();
  
  $a();
  
  $a();
  
  $a();
  
  $a();
  
  $a();
  
  $a();
  
  //123456
  
  ?>。

(编辑:ASP站长网)

    网友评论
    推荐文章
      热点阅读