PHP - warning - Undefined property: stdClass - fix?

后端 未结 9 1062
梦毁少年i
梦毁少年i 2020-11-30 05:22

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

相关标签:
9条回答
  • 2020-11-30 06:04

    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);
    
    0 讨论(0)
  • 2020-11-30 06:11

    You can use property_exists
    http://www.php.net/manual/en/function.property-exists.php

    0 讨论(0)
  • 2020-11-30 06:11

    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']
    }
    
    0 讨论(0)
提交回复
热议问题