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

PHP中如何访问嵌套对象成员?PayPal沙箱API数据访问报错求助

Fixing "Trying to get property of non-object" with PayPal Sandbox API + Nested Object Access in PHP

Hey there! Let's sort out this PayPal API issue and get you accessing those nested properties correctly.

First, let's break down why you're seeing that "Trying to get property of non-object" error:
Your current code tries to run json_decode($result) directly, but $payment->execute() returns a PayPal\Api\Payment object, not a raw JSON string. When you pass an object to json_decode(), PHP converts it to the string "Object", which json_decode() can't parse—so $data ends up being null. Trying to access properties on null triggers that notice.

Correct Ways to Convert the Payment Object

You have two solid options to turn the Payment object into something you can easily access:

Option 1: Convert to an Array

Use the SDK's built-in toArray() method to get a nested associative array:

$result = $payment->execute($execute, $apiContext);
$data = $result->toArray();

// Access the total (adjust indices if you have multiple transactions/resources)
$total = $data['transactions'][0]['related_resources'][0]['sale']['amount']['total'];

Option 2: Convert to JSON then Decode to an Object

If you prefer working with objects, use toJSON() to get a valid JSON string first, then decode it:

$result = $payment->execute($execute, $apiContext);
$jsonString = $result->toJSON();
$data = json_decode($jsonString);

// Access the total (again, adjust indices as needed)
$total = $data->transactions[0]->related_resources[0]->sale->amount->total;

How to Access Nested Objects/Arrays in PHP

A quick refresher for working with nested structures:

  • For objects: Use the -> operator to access properties. If a property is an array, use [] to access its elements (e.g., $obj->arrayProperty[0]->nestedProperty).
  • For arrays: Use square brackets [] to access keys/indices (e.g., $arr['arrayKey'][0]['nestedKey']).
  • Always debug first: Print the full structure with var_dump($data) or print_r($data) to see exactly how your data is nested—this helps you avoid guessing the wrong path.

Pro Tip

PayPal's API returns transactions and related_resources as arrays (since there could be multiple), so make sure you're targeting the right index (usually [0] for a single transaction). If you need to handle multiple transactions, loop through the array instead of hardcoding the index.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:52:57