2015-05-04 139 views
4

我有以下代碼,它可以正常工作。 Twitter好友列表正確,但是當最後一項顯示錯誤「注意:試圖獲取非對象的屬性」時顯示4次。如何隱藏錯誤「嘗試獲取非對象的屬性」

由於代碼的工作,因爲它應該,我想辦法隱藏這些錯誤。

$connection = getConnectionWithAccessToken($consumerkey, $consumersecret, $accesstoken, $accesstokensecret); 
$tweets6 = $connection->get("https://api.twitter.com/1.1/friends/list.json?screen_name=".$twitteruser."&count=".$notweets); 
foreach ($tweets6 as $tweet) 
{ 
    for($i = 0; $i < count($tweet); $i++) 
    { 
     echo $tweet[$i] -> name; 
     echo "<br />"; 
    } 
} 
+1

沒有,正常訪問的價值觀,你不會有問題,不要試圖隱藏的錯誤,並嘗試解決這些問題,這是什麼'$ tweet6'包含反正 – Ghost

+0

$ tweets6是對象的列表,它在我的代碼 – user2675041

回答

4

你可以添加一個檢查,如果該對象具有一定的屬性使用其值之前

if (isset($tweet[$i]->name)) { 
    // process 

} 
+0

謝謝,這解決了這個問題! – user2675041

1

替換此:

for($i = 0; $i < count($tweet); $i++) 

與此:

for($i = 0; $i < count($tweet) - 1; $i++) 

編輯

for($i = 0; $i < count($tweet); $i++){ 
    if (isset($tweet[$i]->name)) { 
     echo $tweet[$i] -> name; 
     echo "<br />"; 
    } 
} 

試試這個

+0

定義我已經試過了,它去掉了錯誤,而且最後一個項目 – user2675041

+0

@ user2675041我已經編輯我的代碼,所以請到通過,希望它有助於 –

1

使用簡單,如果之前打印條件..

$connection = getConnectionWithAccessToken($consumerkey, $consumersecret, $accesstoken, $accesstokensecret); 
    $tweets6 = $connection->get("https://api.twitter.com/1.1/friends/list.json?screen_name=".$twitteruser."&count=".$notweets); 
foreach ($tweets6 as $tweet) 
{ 
    for($i = 0; $i < count($tweet); $i++){ 
    if($tweet[$i]){ 
     echo $tweet[$i] -> name; 
     echo "<br />"; 
    } 
    } 
} 
0

的使用,如果爲空阻止該通知。

$connection = getConnectionWithAccessToken($consumerkey, $consumersecret, $accesstoken, $accesstokensecret); 
$tweets6 = $connection->get("https://api.twitter.com/1.1/friends/list.json?screen_name=".$twitteruser."&count=".$notweets); 
foreach ($tweets6 as $tweet) 
{ 
    for($i = 0; $i < count($tweet); $i++) 
    { 
     if(empty($tweet[$i]->name)) continue; 
     echo $tweet[$i]->name; 
     echo "<br />"; 
    } 
} 
0

雖然接受的答案將工作,PHP有property_exists()函數來完成這個工作,會更合適。即使該屬性具有空值,它也會返回true,而isset()不會。

if (property_exists($tweets[$i], "name")) { 
    .... 
} 
相關問題