我花了十多个小时来找出调试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/