PHP - warning - Undefined property: stdClass - fix

2019-01-11 08:49发布

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?

8条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-01-11 09:00
if(isset($response->records))
    print "we've got records!";
查看更多
祖国的老花朵
3楼-- · 2019-01-11 09:00

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']
}
查看更多
霸刀☆藐视天下
4楼-- · 2019-01-11 09:04

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
 {
       ...
 }
查看更多
Bombasti
5楼-- · 2019-01-11 09:15

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.

查看更多
太酷不给撩
7楼-- · 2019-01-11 09:21

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);
}
查看更多
登录 后发表回答