LoginSignup
2
2

More than 1 year has passed since last update.

【PHP】stdClassのオブジェクトの値を取得したいとき(Call to undefined method stdClass::hoge() の対処法)

Posted at

やりたいこと

LaravelでDBから返ってきたstdClassのオブジェクトの値を取得する際、エラーが出てしまったのでメモです。

以下の場合に、'2022-12-04'を取得したい。

// 取得したデータ
$latestDate = array (
    0 => 
    (object) array(
       'MAX(users.created_at)' => '2022-12-04',
    ),
)

エラーが出た

いつものように以下のように書くと、エラーとなりました。

echo $latestDate[0]->MAX(users.created_at); //Call to undefined method stdClass::MAX() {"exception":"[object] (Error(code: 0): Call to undefined method stdClass::MAX() at …

MAX()がプロパティ名ではなく、メソッドだと認識されてしまっています。

解決策

プロパティ名を{''}で囲うと取得することができました。

echo $latestDate[0]->{'MAX(users.created_at)'}; //'2022-12-04'

参考

2
2
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
2
2