Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Fatal Error Call to a member function ... on a non-object

Tags:

php

I'm having an issue with PHP as it keeps throwing the Exception mention in the title. It fails on the following line:

$item->getDescription();

I understand what the error should mean ($item is null). However, $item is not null.

The scenario is as follows: This is a script that syncs products from a supplier to a store. For that purpose, I have created my own class (SimpleProduct). This class has a getDescription() function.

The problem is that the data I'm receiving tend to have a lot of garbage, like items that haven't been filled in yet. The script should skip these items and keep on iterating across the rest of the products. This fatal error kills the entire script.

I've already tried implementind safeguards to prevent this from happening, but it still occurs constantly. Here's the current code (some snippets removed as they arent pertinent to the currect case).

//This is part of a class that performs the sync

public function syncProduct($item) {

    if(empty($item)) { return "Not a product"; }
         else { var_dump($item) }

    $foo = $item->getDescription();
}

When checking the var_dump result, I get an object with some values filled in. Seeing as it is of the correct type (SimpleProduct) and it is not empty/null, I would suspect this error to stop occurring, but it still does.

Also note that several product syncs have already occurred without any errors before this one pops up, so I know the code is valid. Somehow, this specific case slips past my null-checks.

Is my null-check faulty? How can an error for a non-object be thrown when the object in question does exist?

like image 518
Flater Avatar asked Feb 20 '23 15:02

Flater


1 Answers

Instead of checking whether if the variable is empty, why not check whether if it's an instance of SimpleProduct?

if ($item instanceof SimpleProduct)
{

}

http://php.net/manual/en/language.operators.type.php

like image 135
Kemal Fadillah Avatar answered Feb 22 '23 04:02

Kemal Fadillah