You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel报错:stdClass对象无法转换为int 技术求助

问题描述

同步商品数据时突然触发报错:Object of class stdClass could not be converted to int。API返回的商品ID显示为整数类型,但调用GetProductByProductId接口时仍出现该错误。

Client代码

public function GetProductByProductId($productId)
{
    $this->setUrl('https://api.example.com/ws/ProductService.wsdl');
    self::$_parameters['productId'] = $productId;
    return self::$_sclient->GetProductByProductId(self::$_parameters);
}

Controller代码

$service_id = 100;
$productsRaw = $serviceClient->GetProductList();
foreach($productsRaw as $productId){
   $prd = (new serviceClient($service_id))->GetProductByProductId($productId->id);
   if ($prd->result->status == 'failure') {
       $prd = new stdClass();
       $prd->title = $productId->productName;
       ...ect
       $prd->save();
   }
}

商品数据dump结果

11 => {#10239
    +"id": 553355693
    +"productSellerCode": "SD250-480GQN"
    +"title": "Afox SD250-480GQN 2.5" 480 GB SATA 3 SSD"
    +"subtitle": "SD250-480GQN"
    +"price": "1221.00"
    +"displayPrice": "1221.00"
    +"isDomestic": false
    +"saleStatus": 2
    +"approvalStatus": 1
    +"stockItems": {#10240
      +"stockItem": {#10241
        +"sellerStockCode": "SD250-480GQN"
        +"optionPrice": "1221.00"
      }
    }
    +"currencyAmount": "1221.00"
    +"currencyType": 1
  }

问题分析与解决

尽管dump显示id是整数,但SOAP客户端可能在解析API返回数据时,将该整数包装成了stdClass对象(可能是API返回结构微调,或SOAP解析器的自动类型转换导致),导致传递给GetProductByProductId的参数并非纯整数类型。

可以通过以下方式解决:

  • 强制转换为整数:
    $prd = (new serviceClient($service_id))->GetProductByProductId((int)$productId->id);
    
  • 使用intval()函数转换:
    $prd = (new serviceClient($service_id))->GetProductByProductId(intval($productId->id));
    
  • 若上述方法无效,可先检查$productId->id的实际类型:
    var_dump(gettype($productId->id));
    
    如果输出为object,需进一步提取对象内的整数值(比如$productId->id->scalar或类似属性,具体取决于SOAP解析后的结构)。

内容的提问来源于stack exchange,提问作者Ontrable

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 13:17:00