LoginSignup
1
0

More than 5 years have passed since last update.

stdClassをnewしたらPHP Warning: Creating default object from empty value inとなったときの対応方法

Last updated at Posted at 2019-02-26
  • 環境
    • macOS Mojave バージョン10.14.3
    • PHP 7.3.1
    • Laravel Framework 5.7.26

事象 : stdClassをnewしたら警告が出た

controlStdClassArray.php
<?php
namespace App;

class controlStdClassArray
{
    public function createStdClassArrayNew(): array
    {
        $stdobj = new \stdClass();
        $stdobj->name = 'イタリアンパセリ';
        $stdObj->otherName = 'パースレー';
        return $stdobj;
    }
}

$clas = new controlStdClassArray();
var_dump($clas->createStdClassArrayNew());
$ php controlStdClassArray.php 
PHP Warning:  Creating default object from empty value in /path/to/tryPhp/app/controlStdClassArray.php on line 24

Warning: Creating default object from empty value in /path/to/tryPhp/app/controlStdClassArray.php on line 24
object(stdClass)#2 (1) {
  ["name"]=>
  string(24) "イタリアンパセリ"
}

原因 : 変数名の大文字と小文字が間違っているから

恥ずかしい原因ですがかなり気が付かずに調べたので。

PHP: 基本的な事 - Manual
変数名は大文字小文字を区別します。

よって、$stdObj->otherName = 'パースレー';は初期化しないで実行されることとなります。
PHP5.3以降ではstdClassをnew(初期化)しないで実行すると怒られるようになりました。

  • PHP5.3 : PHP Strict Standards: Creating default object from empty value
  • PHP5.4以降 : PHP Warning: Creating default object from empty value

PHP5.4からは即時stdClass生成がWarningエラーを吐くようになった話 | ブログ :: Web notes.log

controlStdClassArray.php
// 省略
        $stdobj = new \stdClass(); // $stdobjの「o」が小文字
        $stdobj->name = 'イタリアンパセリ';
        $stdObj->otherName = 'パースレー'; // $stdobjの「o」が大文字
        return $stdobj;
// 省略

対応 : 同じ変数は大文字小文字を合わせる

controlStdClassArray.php
// 省略
        $stdObj = new \stdClass();
        $stdObj->name = 'イタリアンパセリ';
        $stdObj->otherName = 'パースレー';
        return $stdobj;
// 省略
$ php controlStdClassArray.php 
object(stdClass)#2 (2) {
  ["name"]=>
  string(24) "イタリアンパセリ"
  ["otherName"]=>
  string(15) "パースレー"
}
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0