Texan78
Texan78

Reputation: 687

Addressing "Undefined property: stdClass::" properly

Here is my issue, I am aware why this is happening but, I am unsure how to resolve it as my research on this issue hasn't returned anything valid to my certain issue.

I am making a cURL request and parsing the objects to get their value and then storing it in a variable to insert into a DB later. The HTTP request is from a streaming server. With that said if the stream is not active the object is not present but, if the object is present it is returned like so...

<IsConnected>true</IsConnected>

So in my script I have been parsing the object like so to find if the value of the object is true or false then storing that value in a variable to insert into a DB.

$streamStatus = $obj->isConnected?'true':'false';

While this works great, it is not correct syntax because when the object is not present due to the stream not being active then I get the following errors in my error log by the dozens.

Undefined property: stdClass::$isConnected

So my question is, how can I can I properly address this so I can get it's value of true when it is active and the object is present but false when the object is not present?

EDIT

Here is the full response if the stream is active and what is returned by the request.

<IncomingStream serverName="_defaultServer_">
<ApplicationInstance>_definst_</ApplicationInstance>
<Name>ncopeland</Name>
<SourceIp>rtmp://xx.xxx.xx.xx:xxxxxx</SourceIp>
<IsRecordingSet>false</IsRecordingSet>
<IsStreamManagerStream>false</IsStreamManagerStream>
<IsPublishedToVOD>false</IsPublishedToVOD>
<IsConnected>true</IsConnected>
<IsPTZEnabled>false</IsPTZEnabled>
<PtzPollingInterval>2000</PtzPollingInterval>
</IncomingStream>

Upvotes: 2

Views: 1450

Answers (2)

Marcin Orlowski
Marcin Orlowski

Reputation: 75619

While this works great, it is not correct syntax because when the object is not present

Then simply add the check for object validity prior interacting with it:

$streamStatus = (is_object($obj) && property_exists($obj, 'isConnected') && $obj->isConnected) ? 'true' : 'false';

NOTE that other answers may suggest using isset() for the above but this is wrong as isset() is not correct tool for the task due to the fact how it handles null.

Upvotes: 1

Sitethief
Sitethief

Reputation: 770

How about this?

$streamStatus = (isset($obj->isConnected) && $obj->isConnected)?'true':'false';

Upvotes: 2

Related Questions