14.

【PHPエラー】Object of class stdClass could not be converted to string

編集
この記事の要点
  • Object of class stdClass could not be converted to stringオブジェクトを文字列として扱おうとしたエラー
  • 原因: echo $obj"$obj"、文字列連結 $str . $obj
  • 対処 ①: 必要なプロパティを明示 ($obj->name)
  • 対処 ②: json_encode($obj) で JSON 化
  • 対処 ③: クラスに __toString() マジックメソッド実装

 

エラーの状況

name = "Alice";

echo $obj;
// Error: Object of class stdClass could not be converted to string

// 文字列連結
echo "Hello, " . $obj;
// 同じエラー

// 文字列補間
echo "Name: $obj";
// 同じエラー

// 出力関数で
print($obj);  // 同じエラー

原因

PHP の echo / 文字列連結 (.) / 文字列補間 ("$x") はオペランドを文字列に変換しようとします。stdClass や独自オブジェクトはデフォルトで文字列変換できないため、このエラーが発生します。

対処方法

方法 1: 必要なプロパティを取得

name = "Alice";
$obj->age = 30;

// ✅ プロパティを明示
echo $obj->name;       // → "Alice"
echo "Hello, " . $obj->name;
echo "Name: {$obj->name}, Age: {$obj->age}";

方法 2: var_export / print_r / var_dump

name = "Alice";

// 構造を可視化(デバッグ用)
print_r($obj);
// stdClass Object ( [name] => Alice )

var_dump($obj);
// object(stdClass)#1 (1) { ["name"]=> string(5) "Alice" }

// 文字列として取得
$str = var_export($obj, true);
echo $str;
// stdClass::__set_state(array("name" => "Alice"))

$str = print_r($obj, true);  // 第 2 引数 true で文字列返却

方法 3: json_encode(API 出力など)

name = "Alice";
$obj->age = 30;

echo json_encode($obj);
// → {"name":"Alice","age":30}

// 日本語含む
echo json_encode($obj, JSON_UNESCAPED_UNICODE);
// → 日本語そのまま

// 整形
echo json_encode($obj, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);

方法 4: __toString() マジックメソッド(自作クラス)

name = $name;
        $this->age = $age;
    }

    // __toString を実装
    public function __toString(): string {
        return "User(name={$this->name}, age={$this->age})";
    }
}

$user = new User("Alice", 30);
echo $user;
// → "User(name=Alice, age=30)"

echo "Hello, " . $user;
// → "Hello, User(name=Alice, age=30)"

方法 5: 配列に変換

name = "Alice";
$obj->age = 30;

// オブジェクト → 配列
$arr = (array) $obj;
print_r($arr);
// Array ( [name] => Alice [age] => 30 )

// implode で文字列化
echo implode(", ", $arr);
// → "Alice, 30"

// または http_build_query (URL クエリ風)
echo http_build_query($arr);
// → "name=Alice&age=30"

よくあるシナリオ

シナリオ 1: API レスポンス → ログ出力

シナリオ 2: テンプレートで出力




ユーザー:

ユーザー: name) ?>

シナリオ 3: 連想配列のキャスト

name;    // stdClass の場合

__toString の制限

関連: オブジェクトと配列の混在

類似エラー

エラー意味
Object of class X could not be converted to stringこのページ
Array to string conversion配列の文字列化
Cannot use object of type stdClass as arrayオブジェクトを配列扱い
Trying to access array offset on value of type nullnull を配列扱い
Illegal offset typeキーにオブジェクト等

関連記事

編集
Post Share
子ページ

子ページはありません

同階層のページ
  1. Fatal error: Maximum execution time of 30 seconds exceeded in...
  2. Fatal error: Uncaught Error: Cannot use object of type stdClass as array in ...
  3. Warning: Use of undefined constant ... - assumed '...' (this will throw an Error)
  4. ERROR: Call to undefined method Maatwebsite\Excel\Excel::load()
  5. Maximum execution time of 30 seconds exceeded
  6. Your requirements could not be resolved to an installable set of packages. ... To enable extensions, verify that they are enabled in your .ini files:
  7. could not find driver
  8. the requested PHP extension mbstring is missing from your system.
  9. the requested PHP extension dom is missing from your system.
  10. A non well formed numeric value encountered
  11. Warning: Cannot modify header information - headers already sent by ...
  12. php_network_getaddresses: getaddrinfo failed: Name or service not known
  13. XMLWriter::openUri(): Unable to resolve file path
  14. Object of class stdClass could not be converted to string
  15. Class 'Google_Service_Youtube' not found