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() マジックメソッド実装

 

エラーの状況

<?php
$obj = new stdClass();
$obj->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: 必要なプロパティを取得

<?php
$obj = new stdClass();
$obj->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

<?php
$obj = new stdClass();
$obj->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 出力など)

<?php
$obj = new stdClass();
$obj->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() マジックメソッド(自作クラス)

<?php
class User {
    public string $name;
    public int $age;

    public function __construct(string $name, int $age) {
        $this->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: 配列に変換

<?php
$obj = new stdClass();
$obj->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 レスポンス → ログ出力

<?php
$response = json_decode($apiResponse);  // → stdClass

// ❌ ダメ
error_log("API response: " . $response);

// ✅ 良い
error_log("API response: " . json_encode($response));
error_log("API response: " . print_r($response, true));

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

<?php // Blade ライク
$user = json_decode('{"name": "Alice"}');
?>

<!-- ❌ ダメ -->
<p>ユーザー: <?= $user ?></p>

<!-- ✅ 良い -->
<p>ユーザー: <?= htmlspecialchars($user->name) ?></p>

<!-- 全プロパティ表示 (デバッグ) -->
<pre><?= htmlspecialchars(print_r($user, true)) ?>

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

<?php
// json_decode のデフォルトは stdClass
$data = json_decode($json);  // ← stdClass

// 連想配列で受け取りたい
$data = json_decode($json, true);  // ← 第 2 引数 true

// 利用
echo $data["name"];  // 配列としてアクセス
echo $data->name;    // stdClass の場合

__toString の制限

<?php
class MyClass {
    public function __toString(): string {
        // ❌ 例外を投げると致命的エラー (PHP 7.4 以前)
        throw new Exception("Error");
    }
}

// PHP 8+ は __toString 内の例外を許容

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

<?php
// stdClass vs 連想配列の判別
function isAssocArray($value): bool {
    if (!is_array($value)) return false;
    if (empty($value)) return false;
    return array_keys($value) !== range(0, count($value) - 1);
}

function isStdClass($value): bool {
    return is_object($value) && get_class($value) === 'stdClass';
}

// 安全に文字列化
function toStringValue($value): string {
    if (is_string($value)) return $value;
    if (is_scalar($value)) return (string) $value;  // int, float, bool
    if (is_null($value)) return "";
    if (is_array($value) || is_object($value)) {
        return json_encode($value, JSON_UNESCAPED_UNICODE);
    }
    return "";
}

類似エラー

エラー意味
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