我有一個 PHP 7.3 中具有受保護屬性的類。該類有一個__get()方法設置為返回屬性,但不允許更改它們。非?;荆篊lass 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; }}}我有一個對數(shù)組和對象進行排序的函數(shù)。在該代碼中,我有一些選擇要排序的值。如果它是一個數(shù)組,則獲取該元素。如果是對象,則查找函數(shù),如果沒有函數(shù),則查找屬性:$ae = is_array( $a ) ? $a[ $arg ] : ( is_callable( [$a, $arg] ) ? $a->$arg() : $a->$arg );所以我運行了一個測試,調(diào)用對象的只讀屬性之一——“名稱”。如果我直接調(diào)用它,$myObj->name將返回預期的值。$a = $myObj如果我使用and將其傳遞到排序函數(shù)中$arg = "name",我確實會返回該值(即,它排序正確),但我也會收到該屬性不存在的錯誤。Call to nonexistent 'name' property of myClass class所以...“變量變量”屬性名稱工作正常,并且按照我的預期傳遞函數(shù)__get(),但它仍然會 ping 錯誤。薛定諤財產(chǎn)既存在又不存在。它觸發(fā)if()中子句的兩個分支__get()。注意:我將排序代碼分解為多行以查明錯誤。它肯定在第三行—— $a->$arg。如果我將其更改為( $a->$arg ?? null )它會給出完全相同的錯誤。記?。核诜祷刂担坏瑫r記錄一個錯誤,表明沒有這樣的值。這里發(fā)生了什么?我該如何擺脫這個錯誤?
1 回答

慕桂英546537
TA貢獻1848條經(jīng)驗 獲得超10個贊
好的,發(fā)生的事情是這樣的:該錯誤僅在排序時針對某些條目觸發(fā),而不是針對全部條目。(日志中有大量此類錯誤,因此僅從外觀上看并不明顯。)
看__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;
}
}
來自數(shù)據(jù)庫的一些數(shù)據(jù)具有空白字段,這對于代碼來說是空的。 isset( null )是一個 false-y 值,因此elseIf 的子句在這些條目上觸發(fā)。
修復?不檢查isset(),檢查property_exists()。
public function __get( $prop ) {
if ( property_exists( $this, $prop ) ) {
...
- 1 回答
- 0 關注
- 133 瀏覽
添加回答
舉報
0/150
提交
取消