2013-03-18 30 views
0

我在for循環中創建了同一個類的實例。但似乎這些實例以某種方式引用同一個對象。兩個php對象引用同一個實例

這是代碼;

class Content{ 
    /** 
    * current content id 
    * @var int 
    */ 
    public $id; 

    function __construct($id){ 
     echo " <br>Construct content ".$id; 
    } 

    function createContentOfPage($id){ 
     $contentIdArray = $this->dbo->getContentIdsForPage($id); 
     /*var_dump of $contentIdArray aray is given below*/ 
     if(is_array($contentIdArray) && count($contentIdArray)>0){ 
     $contentArray = array();  
      foreach ($contentIdArray as $Id){ 
       echo "<br>Content id: ".$Id['content_id']; 
       array_push($contentArray, new Content(($id['content_id']))); 
      } 

     } 
    } 
} 

這裏是$ contentIdArray的後續代碼var_dump

array(2) { 
    [0]=> 
    array(1) { 
    ["content_id"]=> 
    string(1) "1" 
    } 
    [1]=> 
    array(1) { 
    ["content_id"]=> 
    string(1) "2" 
    } 
} 

如果我跑這裏createContentOfPage()是放出來;

Content id: 1 
Construct content 1 
Content id: 2 
Construct content 1 

什麼是我在這裏做錯了?請幫忙。

+1

您一定會同時使用'$ Id','$ id'和成員變量'$ id'來混淆某人。 – 2013-03-18 11:48:30

回答

1

嘛,你使用不同的ID變量:

echo "<br>Content id: ".$Id['content_id']; 
array_push($contentArray, new Content(($id['content_id']))); 

二者必選其一$Id$id一致 - 在這種情況下,你需要使用$Id


你應該避免像這樣的陰影變量的做法。調用數組迭代器變量$contentId和您的參數$pageId,或類似的東西。

+0

好!現在我感覺自己像是在阻礙自己... :(( 謝謝你) – 2013-03-18 11:51:32

相關問題