2010-03-18 132 views
41

我在我的錯誤日誌中得到這個警告,並想知道如何在我的代碼中糾正這個問題。PHP - 警告 - 未定義的屬性:stdClass - 修復?

警告: PHP公告:未定義的屬性:在script.php的stdClass的:: $記錄上線440

一些代碼:如果存在記錄

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 
) 

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

響應如果記錄不存在則回覆

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

我在想像array_key_exists()的功能,但對於對象,什麼?還是我以這種錯誤的方式去做?

回答

93
if(isset($response->records)) 
    print "we've got records!"; 
+0

可以 「或」 以某種方式使用?例如:$ foo = $ bar-> foo或「default」; – Hontoni 2013-03-05 17:30:11

+1

您可以使用Elvis $ role_arr = getRole($ response-> records)?:[]; – Pierre 2013-08-07 13:42:03

2

本身似乎有記錄的大小的響應。您可以使用它來檢查是否存在記錄。喜歡的東西:

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

如果認爲這將工作:

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

新定義根據企業的性質也包括在內。

4

如果你想使用property_exists,你需要用get_class()

獲得類的名稱在這種情況下,這將是:

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

在這種情況下,我會用:

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

你不會得到任何醜陋的通知,如果屬性不存在,你就會知道你其實已經有了一些記錄與工作,即。 $ response->記錄不是一個空數組,NULL,FALSE或任何其他空值。

-1

替代方法:只需使用'@'運算符來消除警告。

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

參見:http://php.net/manual/en/language.operators.errorcontrol.php

+1

這不是好習慣,不要這樣做。代碼乾淨。 – iLLin 2015-02-12 02:02:44

+1

這是一個意見問題;我不會建議使用@來沉默來自某個方法的警告,但作爲避免bazillion isset()調用的方法,它很方便,工作,並且恕我直言,使代碼更清潔,更易讀。因人而異。 – burlyearly 2015-03-05 22:52:25

5

isset()函數是罰款最高水平,但空()是有用得多找到嵌套的值是否設置。例如:

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

或者:

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