syntax - PHP类方法中使用的 undefined variable 没有错误

标签 syntax syntax-error php

我花了十多个小时来找出调试PHP程序的错字。我希望PHP在使用 undefined variable 时会产生错误。但是,当将其用作方法中的对象时,则不会。有什么理由吗?

<?php

    $oClass = new MyClass;
    // $oCless->tihs('key', 'taht');    //<-- triggers the error: Notice: Undefined variable
    $oClass->tihs('key', 'taht');
    echo $oClass->arr['key'];

    class MyClass {
        public $arr = array('key' => 'foo');

        function tihs($key, $value) {
            $tihs->arr[$key] = $value;  //<-- this does not cause an error message.
        }
    }
?>

最佳答案

通常,如果错误报告级别设置为E_ALL | E_STRICT(或从PHP 5.4.0开始为E_ALL),则应吐出E_STRICT错误。例如,此代码:

error_reporting(E_ALL | E_STRICT);
$tihs->adrr = 453;  

产生:
Strict Standards: Creating default object from empty value in [...]

有趣的是,如果您专门创建数组而不是普通变量作为不存在的对象的属性,例如:
error_reporting(E_ALL | E_STRICT);
$tihs->adrr[25] = 453;  

没有显示严格的标准错误!看来这很可能是PHP人士可能想要解决的问题,因为我不知道这个记录在案,我也不认为这种行为有正当的理由。

作为记录,在两种情况下,无论错误如何,都将即时创建新的stdClass,就像his answer中提到的sberry一样。

关于syntax - PHP类方法中使用的 undefined variable 没有错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12274297/

相关文章:

android - Android View 标记何时需要结束标记?

javascript - 对象/函数/类声明周围的括号是什么意思?

java - Java中特定的字符串输入

php - PHP 是否能够在循环内缓存计数调用?

php - PSR4 不工作

PHP语法替代品?

c++ - 为什么这个语法无效? vector 指针->[0]

python - 我的 python 解释器不识别字符串

python-2.7 - Python : “SyntaxError: invalid syntax” for arithmetic

php - 如何在分页 CodeIgniter 函数中使用参数?