I’m using the output from an API. The data extracted is processed in one of my Classes. The output is similar to this:
stdClass Object ( [status] => error [redirect_url] => stdClass Object ( [web] => https://example.com/signup.php ) )
I use the above in my own class $siteItems->processData($output->status, $output->answer)
;
However when the data isn’t available I get Trying to get property 'answer' of non-object
. When I use isset and there is a bad request $siteItems->processData(isset($output->status), isset($output->answer))
I don’t get this.
Is there a way to use $siteItems->processData($output->status, $output->answer) and only use isset inside of my own class instead having to use it when calling the function.
Advertisement
Answer
If processData()
is in your own class so you can change the implementation why not just have the object passed instead of the properties …
$siteItems->processData($output);
and in your class where processData()
is defined, use the ternary operator to set the variable or null otherwise. You can then check them in an if
and perform actions based on whether they exist or not:
public function processData($obj) { $status = (!is_null($obj->status)) ? $obj->status: null; $answer = (!is_null($obj->answer)) ? $obj->answer : null; if($status != 'error' && $answer) { // do stuff } }