name_masked
name_masked

Reputation: 9794

is_null in PHP still returns null?

All,

I have the following code:

public function addElements()
{
     $newArray = array();
     for ($index = 0 ; $index < count($this->listOfElements) ; $index++)
     {
           $temp = $this->listOfElements[$index];
           if (!is_null($temp) && !is_null($temp->getPlayerOb()))
           {
              echo "Player Name is: ".$temp->getPlayerOb()->getName();
              array_push($newArray, $temp);
           }
     }
}

The error line is if (!is_null($temp) && !is_null($temp->getPlayerOb())) and stack says:

Call to a member function getPlayerOb() on a non-object

I am not able to understand the issue here since I am trying to skip null values

Upvotes: 1

Views: 164

Answers (1)

lonesomeday
lonesomeday

Reputation: 237845

$temp is clearly a non-object value that isn't null. I don't know what listOfElements is, but perhaps accessing a non-existing key gives false rather than null.

You might check with is_object instead:

if (is_object($temp) && !is_null($temp->getPlayerOb()))

It would be better, however, to check positively. Check with instanceof and the class name:

if (($temp instanceof SomeClass) && !is_null($temp->getPlayerOb()))

Upvotes: 6

Related Questions