dtn36013 2017-01-24 22:22
浏览 64

什么是控制变量绑定在闭包中的php设置?

the following two pieces work on two separate machines.
Both machines are php5.5.x (not sure what is x).
i.e. one work on one machine only and the other one on both (the one with use).
Notice the use of the keyword **use** in the second version. Sadly, I have no command line access to those machines to check php settings.
version one

$a = 1;
$b = function(){
   echo $a;
};
$b();

version two:

$a = 1;
$b = function() use($a){
   echo $a;
};
$b();
  • 写回答

1条回答 默认 最新

  • dovs36921 2017-01-24 22:38
    关注

    Your first closure is experiencing a variable scope issue, $a does not exist inside the closure. You can fix this by:

    1. defining global $a inside of the closure.
    2. Use the use keyword as in your second example.
      • Only available in PHP version >= 5.3
    3. Use arguments instead
      • echo (function($a){ echo $a; })("test");

    You should enable error reporting to see why your first closure should not work in the first place

    ini_set("display_errors", 1);
    error_reporting(-1);
    
    $a = 1;
    $b = function(){
      echo $a; // Notice: Undefined variable: a in /path/to/script.php on line #
    };
    $b();
    

    If both hosts are running PHP 5.5, the output should be the same. It might be that 1 is suppressing the notice messages and the other is not. If that's the case, the ini settings you should be looking for are:

    error_reporting
    display_errors
    

    And as shown above, you can simply change those settings at script run-time by using ini_set() where error_reporting(-1) is a simple shortcut to ini_set('error_reporting', E_ALL | E_STRICT)

    评论

报告相同问题?

悬赏问题

  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害