PHP中如何访问嵌套对象成员?PayPal沙箱API数据访问报错求助
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)orprint_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

