All Articles

PHP5.4からは即時stdClass生成がWarningエラーを吐くようになった話

短いですが、メモ程度に書いておきます。

2013/06/06 Codeigniterのエラー処理について追記しました

かなり前からCodeIgniterで、stdClassを即時生成してプロパティを生やすコードを書いてました。

``` $data->hoge = 'huga';

this>load>view(view,this->load->view('view',data);

<p>みたいなコードです。誰かのコードを参考にした記憶があるんですが、まぁそれはいいとして。
CIを使ってる方なら同じような書き方をしてるかもしれません。あ、してないならいいですすいません。</p>
<h3>PHP5.3はStrictエラー</h3>
<p>これが通用するのはPHP5.2までなんですね。PHP5.3からはStrict Errorの警告が出ます。</p>

PHP5.3.21

$data->hoge = ‘huga’;

=> PHP Strict Standards: Creating default object from empty value

<p>まぁStrict違反だしまぁいいかー…と思ってたんですが(いや、エラーは無い方がいいんですけどね)</p>

<p style="color:red">[追記]</p>
<p>
<strong>「いや、そもそもPHP5.3.xで気付かない方がおかしくない?」</strong>と思われた方もいるかもしれません。実は、CodeIgniter上でコーディングしている場合はこのエラーは出ないのです。だから気が付かなかった。

CodeIgniterは、独自のエラーハンドラー内で<strong>Strictエラーをもみ消す</strong>という処理を行なっています。(もみ消す、という表現が正しいかはさておき)私の手元のCI2.1.3でも確認できました。具体的には、system/core/Common.phpの_exception_hanlder()関数の中です。</p>

if ( ! functionexists(’exceptionhandler’)) { function _exceptionhandler(severity,severity,message, filepath,filepath,line) { // We don’t bother with “strict” notices since they tend to fill up // the log file with excess information that isn’t normally very helpful. // For example, if you are running PHP 5 and you use version 4 style // class functions (without prefixes like “public”, “private”, etc.) // you’ll get notices telling you that these have been deprecated. if ($severity == E_STRICT) { return; }

            $_error =& load_class('Exceptions'undefined 'core');

            // Should we display the error? We'll get the current error_reporting
            // level and add its bits with the severity bits to find out.
            if (($severity & error_reporting()) == $severity)
            {
                    $_error->show_php_error($severityundefined $messageundefined $filepathundefined $line);
            }

            // Should we log the error?  No?  We're done...
            if (config_item('log_threshold') == 0)
            {
                    return;
            }

            $_error->log_exception($severityundefined $messageundefined $filepathundefined $line);
    }

}

<p>ということで、$severtyにはエラーレベルが入りますが、それがE_STRICTの場合はreturnしてエラーを吐かずに握りつぶしているようです。個人的にはFWがそこまで面倒見るよりは、ダメなものはダメって警告は出してくれる方がいいような気もしますが…

とまぁ、そんなわけでCodeIgniter上ではStrictエラーは表示されないようになっているので、他のFWで途端にエラーが出たりするかもしれません。エラーのでないコードを心がけたいですね(自戒)</p>

<h3>PHP5.4からはWarningエラー</h3>
<p>なんとPHP5.4からはエラーレベルがWarningまで上がってるんですねー(;´Д`)</p>

PHP5.4.11

$data->hoge = ‘huga’;

=> PHP Warning: Creating default object from empty value

<p>さすがにWarningだとerror_reportingで消すのも憚られるレベルなので、ちゃんとstdClassで初期化しなさいよ、という話でした。</p>

PHP5.4.11

data=newstdClass;data = new stdClass;data->hoge = ‘huga’;

=> ( ´∀`)b

<p>これならOKですね。あ、顔文字は出ませんけど。</p>