V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
xlinux
V2EX  ›  问与答

请教一下 PHP8 的报错信息与 PHP7 的区别

  •  
  •   xlinux · 10 天前 · 582 次点击

    test.php 文件内容如下:

    <?php
        $arr = [];
        var_dump($arr['pay-ip']);
    

    然后通过不同的 PHP 版本去允许该代码:

    root@iZuf67mcw0tro6podzt9fcZ:~# /www/server/php/74/bin/php /www/wwwroot/themes.example.com/test.php
    NULL
    root@iZuf67mcw0tro6podzt9fcZ:~# /www/server/php/83/bin/php /www/wwwroot/themes.example.com/test.php
    PHP Warning:  Undefined array key "pay-ip" in /www/wwwroot/themes.example.com/test.php on line 3
    
    Warning: Undefined array key "pay-ip" in /www/wwwroot/themes.example.com/test.php on line 3
    NULL
    root@iZuf67mcw0tro6podzt9fcZ:~# 
    

    一:运行的 test.php 代码是一样的 二:PHP7 没有警告信息,PHP8 有警告信息 三:PHP7 与 PHP8 的 php.ini 在以下两个参数的配置一致

    display_errors = On
    error_reporting = E_ALL & ~E_NOTICE
    

    为啥 PHP8 报警告而 PHP7 没有报?是不是 php.ini 还有哪些参数影响了?还是说 PHP8 的报错处理机制改变了?有相关的参考链接可以看看吗?

    第 1 条附言  ·  10 天前
    原来 undefined array key 在 PHP7 报错等级是 E_NOTICE ,在 PHP8 中等级变成 E_WARNING ,又因为 php.ini 的 error_reporting 配置为 E_ALL & ~E_NOTICE ,所以在报错信息在这两个不同版本有了不同的处理。
    第 2 条附言  ·  10 天前
    7 条回复    2024-05-13 01:25:14 +08:00
    ysc3839
        1
    ysc3839  
       10 天前   ❤️ 1
    你的目的是什么?是想使用 PHP7 的时候也能报错方便调试吗?
    如果只是为了消除警告,在 $arr 前面加上 @ 就好了,比如 var_dump(@$arr['pay-ip']);
    maigebaoer
        2
    maigebaoer  
       10 天前 via Android   ❤️ 1
    https://github.com/php/php-src/issues/8906 PHP 7 和 8 的报错等级变更问题
    jianchang512
        3
    jianchang512  
       10 天前   ❤️ 2
    https://www.php.net/manual/zh/migration80.incompatible.php

    8.0 就改变了。



    ```
    一些通知已转换为警告:

    尝试读取未定义的变量。
    尝试读取未定义的属性。
    尝试读取未定义的数组 key 。
    尝试读取非对象的属性。
    尝试读取非数组的数组索引。
    尝试转换数组为字符串。
    尝试使用资源作为数组 key 。
    尝试使用 null 、bool 、float 作为字符串 offset 。
    尝试读取越界的字符串 offset 。
    尝试将空字符串分配给字符串 offset 。

    ```
    xlinux
        4
    xlinux  
    OP
       10 天前
    @ysc3839 谢谢,我是想了解 PHP8 与 PHP7 在这方便处理的差异。
    xlinux
        5
    xlinux  
    OP
       10 天前
    xlinux
        6
    xlinux  
    OP
       10 天前
    @maigebaoer 懂了,原来 undefined array key 在 PHP7 报错等级是 E_NOTICE ,在 PHP8 中等级变成 E_WARNING ,又因为 php.ini 的 error_reporting 配置为 E_ALL & ~E_NOTICE ,所以在报错信息在这两个不同版本有了不同的处理。
    NewYear
        7
    NewYear  
       10 天前
    php 最烦的就是调试,同样的错误级别,有时候页面 500 ,什么信息都不输出,完全不知道哪里出问题……
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   2768 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 15:05 · PVG 23:05 · LAX 08:05 · JFK 11:05
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.