dsfew215211 2017-07-28 12:53
浏览 31
已采纳

$ foo [“bar”] = 1; 如果$ foo不存在,我可以请PHP抱怨吗?

Take this line of PHP:

$foo["bar"] = 1;

I would like PHP to throw an exception if $foo doesn't exist. Right now, it doesn't throw an exception, or even print an error or warning even with display_errors set to 1 and error_reporting called with E_ALL. Instead, it creates an array $foo and sets $foo["bar"] to 1, even though the variable $foo did not exist beforehand.

Is there something like declare(strict_types=1); that will enable checking this?

The reason I want this is so that I can more easily detect typos when I accidentally misspell a variable name.

  • 写回答

4条回答 默认 最新

  • dongyanju0945 2017-07-28 13:01
    关注

    Unfortunately, you are setting up an array with the command. Why would php throw an exception if you are setting up this?

    It's like assigning a value to a variable and then asking why did PHP assign the value to the variable?

    $foo["bar"] = 1;
    
    print_r($foo);
    // This prints the following: 
    // Array ( [bar] => 1 )
    

    The correct way of checking would be:

    if(isset($foo))
    {
      $foo['bar'] = 1;
    }
    else
    {
      // do something if $foo does not exist or is null
    }
    

    Hope this helps! In short the answer to your question is no: there isn't a way to make PHP throw an exception or print a warning in your example.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧