报错“Trying to get property of non-object”含义及代码问题排查求助
First off, let's break down what this error actually means: You’re trying to access a property using the -> operator on something that isn’t an object. Put simply, you wrote code like $myVar->someProperty, but $myVar isn’t an instance of a class—it could be null, an array, a string, a number, or even an undefined variable. PHP throws this notice because only objects have properties to access with the -> syntax.
Now let’s troubleshoot your specific error from MatchPopulate.php line 20:
Step 1: Locate the problematic line
Open MatchPopulate.php and jump straight to line 20. You’ll see code that uses the -> operator—something like $match->teamName or $result->matchId. That’s the line where the issue is occurring.
Step 2: Debug the variable in question
Right before line 20, add a quick debug check to see what your variable actually is. For example, if line 20 is $team = $match->team;, add this above it:
// Debug: Check what $match contains var_dump($match); die; // Stop execution to view the output
Run your code again, and you’ll likely see one of these common scenarios:
- It’s
null: This means the object you expected wasn’t created or fetched successfully. Maybe your database query returned no results, a function call failed to return an object, or you forgot to instantiate a class withnew. - It’s an array: You’re using the wrong syntax! Arrays use square brackets (
$myArray['key']) instead of->. Fix your code to use array access instead of object property access. - It’s a string/number/other primitive type: You’ve mixed up variables—this variable was never meant to be an object. Double-check where this variable comes from and what it’s supposed to hold.
Step 3: Trace the variable’s origin
Once you know what the variable is, track back to where it’s set:
- If it’s from a database query: Verify your SQL is correct, and that it actually returns rows. For example, if you’re using an ORM,
first()returnsnullwhen no matches are found—always check if the object exists before accessing its properties. - If it’s from a function call: Check the function’s return value. Does it promise to return an object, but sometimes returns
nullor something else? - If it’s from
json_decode(): Remember thatjson_decode()returns an object by default, but if the JSON is invalid or empty, it returnsnull. If you meant to get an array, passtrueas the second parameter.
Example Fix
Suppose your line 20 is:
$matchDate = $match->date;
And your debug shows $match is null (because your query found no matches). A quick, safe fix would be to add a check first:
if ($match instanceof stdClass || $match instanceof YourMatchClass) { $matchDate = $match->date; } else { // Handle the missing object case—set a default or log an error $matchDate = 'No match found'; }
内容的提问来源于stack exchange,提问作者DaveTheGolfer

