薛定谔&x27;s property:PHP类属性名和`u get()`返回值,但也返回";不';“不存在”;错误

薛定谔&x27;s property:PHP类属性名和`u get()`返回值,但也返回";不';“不存在”;错误,php,Php,我在PHP7.3中有一个类,它有一个受保护的属性。该类设置了一个\uu get()方法来返回属性,但不允许对其进行更改。非常基本: Class myClass { protected $name; ... public function __get( $prop ) { if ( isset( $this->$prop ) ) { return $this->$prop; } else { error_log( "Call

我在PHP7.3中有一个类,它有一个受保护的属性。该类设置了一个
\uu get()
方法来返回属性,但不允许对其进行更改。非常基本:

Class myClass {
protected $name;

...

public function __get( $prop ) {
    if ( isset( $this->$prop ) ) {
        return $this->$prop;
    } else {
        error_log( "Call to nonexistent '$prop' property of " . __CLASS__ . " class" )
        return null;
    }
}

}
我有一个对数组和对象进行排序的函数。在这段代码中,我有一点选择排序的值。如果是数组,则获取该元素。如果是对象,则查找函数;如果没有函数,则查找属性:

$ae = is_array( $a ) ? $a[ $arg ] :
    ( is_callable( [$a, $arg] ) ? $a->$arg() :
    $a->$arg );
所以我运行了一个测试,调用对象的一个只读属性--“name”

如果我直接调用它,
$myObj->name
会按预期返回一个值

如果我用
$a=$myObj
$arg=“name”
将其传递到排序函数中,我会返回值(即,它正确排序),但我也会得到属性不存在的错误

调用myClass不存在的'name'属性

所以。。。“variable-variable”属性名工作正常,正如我所期望的那样通过
\uu get()
函数,但它仍在ping错误。薛定谔的性质既存在又不存在。它触发了
\uu get()
中的
if()
子句的两个分支

注意:我在多行上断开了排序代码以查明错误。它肯定在第三行--
$a->$arg
。如果我将其更改为
($a->$arg??null)
,则会给出完全相同的错误。记住:它是在返回值;但同时记录一个错误,说明没有这样的值


这是怎么回事?如何消除此错误?

好的,下面是发生的情况:在排序时,错误只针对部分条目触发,而不是所有条目。(日志中有大量此类错误,因此仅从外观上看并不明显。)

查看
\uu get()
代码:

public function __get( $prop ) {
    if ( isset( $this->$prop ) ) {
        return $this->$prop;
    } else {
        error_log( "Call to nonexistent '$prop' property of " . __CLASS__ . " class" )
        return null;
    }
}
来自数据库的一些数据有空白字段,代码认为这些字段为空
isset(null)
是一个false-y值,因此If的
else
子句对这些条目触发

修复?不要检查
isset()
,检查
属性\u exists()


无法复制(PHP7.4)。你确定它很好吗?如果只是一些因素,那可能是偶然的。这能回答你的问题吗@哎呀,事情就是这样。我昨天就想出来了,但在明天之前我不接受我自己的答案。我认为最好接受副本,因为信息是适当链接的。祝你好运
public function __get( $prop ) {
    if ( property_exists( $this, $prop ) ) {
...