Strange Error Trying To Get Property Of Non-Object

I’m getting this error:


Trying to get property of non-object

in this piece of code:




foreach ($this->ordensServicoPendentes as $os)

{

    $op = $os->op;

    $linhaGrid = array();

    $linhaGrid['codigoOP'] = $op->codigo;


    echo $linhaGrid['codigoOP'] . "<BR>";

}



My first thought was that $op was null, so I did:




foreach ($this->ordensServicoPendentes as $os)

{

    $op = $os->op;

    $linhaGrid = array();

    $linhaGrid['codigoOP'] = ($op != null) ? $op->codigo : "NULL";


    echo $linhaGrid['codigoOP'] . "<BR>";

}



But, for my surprise, it prints $op->codigo in every line and not a single NULL.

What could be the problem?

You checked the $op->codigo line… but this error can happen on $os->op, too.

Also it can happen that $op is something else (not an object and not null)… like an array.

Thanks for you answer.

I think you misunderstood me.

When i do


$linhaGrid['codigoOP'] = ($op != null) ? $op->codigo : "NULL";

it works. But doesn’t make sense to me why


 $linhaGrid['codigoOP'] = $op->codigo;

doesn’t work.

I checked $op and it is an object and not null

Use "$op !== null" or is_null() to properly check for null value.

Using




if (is_object($op) && !is_null($op))

{

    echo "OK <BR>";

}

else

{

    echo "NOT OK <BR>";

}



prints OK for every line.

$op is not an array, i checked