PHP出现Object of class stdClass could not be converted to string报错求助
问题排查结果
直接报错原因
报错触发自代码中的Log::debug($responsible->contactInfo);行:$responsible->contactInfo为stdClass类型对象,Monolog日志组件写入日志时会尝试将输入参数转换为字符串,普通stdClass未实现__toString()魔术方法,无法直接转为字符串,因此抛出对应错误。
从日志顺序也可验证:最后一条正常执行的日志是--- create ---,下一行要打印$responsible->contactInfo时直接触发报错,完全符合错误触发逻辑。
潜在风险点
你代码中直接遍历$responsible->contactInfo对象,虽然PHP支持遍历stdClass的公共属性,但存在兼容性风险,建议统一转成数组后再遍历。
修复方案
- 调整日志打印代码,将stdClass转为可打印的字符串格式:
// 方案1:用print_r输出结构化内容,第二个参数传true返回结果而非直接打印 Log::debug(print_r($responsible->contactInfo, true)); // 方案2:转成json字符串打印 Log::debug(json_encode($responsible->contactInfo));
- (可选优化)遍历前将contactInfo转成数组,避免遍历对象的潜在问题:
if (isset($responsible->contactInfo)) { foreach ((array)$responsible->contactInfo as $key => $value) { if ($value && property_exists($value, 'type') && $value->type == 'email') { $email = $value->value; } if ($value && property_exists($value, 'type') && $value->type == 'phone') { $phone = preg_replace('/[^0-9]/', '', $value->value); } } }
内容的提问来源于stack exchange,提问作者Andrii Shinkarenko
相关产品推荐
相关产品推荐

