down123321123 2012-09-05 03:57
浏览 32
已采纳

PHP中的类方法中使用的未定义变量没有错误

I spent more than 10 hours to find out the typo for debugging my PHP program. I expected PHP would produce an error when using an undefined variable. But when it is used as an object in a method, it doesn't. Is there a reason for it?

<?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.
        }
    }
?>
  • 写回答

4条回答 默认 最新

  • doujie9882 2012-09-05 04:28
    关注

    Normally if the error reporting level is set to E_ALL | E_STRICT (or E_ALL as of PHP 5.4.0) it should spit out an E_STRICT error. For instance, this code:

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

    Produces:

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

    Interestingly enough, if you specifically create an array instead of an ordinary variable as a property of an object that doesn't exist, e.g.:

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

    No strict standards error is shown! It looks like this could potentially be something PHP folks might want to fix, because I'm not aware this is documented nor I think there's a legitimate reason for this behaviour.

    For the record, in both cases regardless of the error a new stdClass is being created on the fly instead, like sberry mentions in his answer.

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

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?