[php] PHP - warning - Undefined property: stdClass - fix?

I get this warning in my error logs and wanted to know how to correct this issues in my code.

Warning: PHP Notice: Undefined property: stdClass::$records in script.php on line 440

Some Code:

// Parse object to get account id's
// The response doesn't have the records attribute sometimes.
$role_arr = getRole($response->records);  // Line 440 

Response if records exists

stdClass Object
(
    [done] => 1
    [queryLocator] =>
    [records] => Array
        (
            [0] => stdClass Object
                (
                    [type] => User
                    [Id] =>
                    [any] => stdClass Object
                        (
                            [type] => My Role
                            [Id] =>
                            [any] => <sf:Name>My Name</sf:Name>
                        )

                )

        )

    [size] => 1
)

Response if records does not exist

stdClass Object
(
    [done] => 1
    [queryLocator] =>
    [size] => 0
)

I was thinking something like array_key_exists() functionality but for objects, anything? or am I going about this the wrong way?

This question is related to php object warnings

The answer is


Depending on whether you're looking for a member or method, you can use either of these two functions to see if a member/method exists in a particular object:

http://php.net/manual/en/function.method-exists.php

http://php.net/manual/en/function.property-exists.php

More generally if you want all of them:

http://php.net/manual/en/function.get-object-vars.php



If think this will work:

if(sizeof($response->records)>0)
$role_arr = getRole($response->records);

newly defined proprties included too.


Error control operator

In case the warning is expected you can use the error control operator @ to suppress thrown messages.

$role_arr = getRole(@$response->records);

While this reduces clutter in your code you should use it with caution as it may make debugging future errors harder. An example where using @ may be useful is when creating an object from user input and running it through a validation method before using it in further logic.


Null Coalesce Operator

Another alternative is using the isset_ternary operator ??. This allows you to avoid warnings and assign default value in a short one line fashion.

$role_arr = getRole($response->records ?? null);

isset() is fine for top level, but empty() is much more useful to find whether nested values are set. Eg:

if(isset($json['foo'] && isset($json['foo']['bar'])) {
    $value = $json['foo']['bar']
}

Or:

if (!empty($json['foo']['bar']) {
    $value = $json['foo']['bar']
}

The response itself seems to have the size of the records. You can use that to check if records exist. Something like:

if($response->size > 0){
    $role_arr = getRole($response->records);
}

If you want to use property_exists, you'll need to get the name of the class with get_class()

In this case it would be :

 if( property_exists( get_class($response), 'records' ) ){
       $role_arr = getRole($response->records);
 }
 else
 {
       ...
 }

In this case, I would use:

if (!empty($response->records)) {
 // do something
}

You won't get any ugly notices if the property doesn't exist, and you'll know you've actually got some records to work with, ie. $response->records is not an empty array, NULL, FALSE, or any other empty values.


Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to object

How to update an "array of objects" with Firestore? how to remove json object key and value.? Cast object to interface in TypeScript Angular 4 default radio button checked by default How to use Object.values with typescript? How to map an array of objects in React How to group an array of objects by key push object into array Add property to an array of objects access key and value of object using *ngFor

Examples related to warnings

numpy division with RuntimeWarning: invalid value encountered in double_scalars libpng warning: iCCP: known incorrect sRGB profile How to use _CRT_SECURE_NO_WARNINGS C pointers and arrays: [Warning] assignment makes pointer from integer without a cast Server configuration by allow_url_fopen=0 in IntelliJ IDEA shows errors when using Spring's @Autowired annotation Warning :-Presenting view controllers on detached view controllers is discouraged Data truncated for column? Warning message: In `...` : invalid factor level, NA generated How to suppress warnings globally in an R Script