2012-03-13 67 views
0

我有一個foreach循環和引用的奇怪問題。 這裏是我的代碼:PHP foreach循環奇數引用行爲

$authors = array(                                       
     new Author(array('first_name'=>'Name 1','last_name'=>'last name 1')),                           
     new Author(array('first_name'=>'name 1','last_name'=>'last name 2')),                         
);                                           

    foreach($authors as $key => $author){                                     
    $authors[$key] = Author::manager()->getOrCreate($author);                              
    print $author->id."-".$authors[0]->id."<br>";                                                                
    }     

因此,如果我們假設這兩個對象在數據庫中創建,然後顯示輸出:

1-1 
2-2 

當你想我的問題是:爲什麼$authors[0]->id是指$author->id ?? 我想這是一個引用問題,但由於我沒有在foreach循環中使用引用,所以我不知道它來自哪裏!

任何建議將受到歡迎。 謝謝

+0

你確定輸出不1-1,2-1?看起來這就是它輸出的內容。只想確認一下? – 2012-03-13 19:06:06

+0

由於您在創建$ authors數組時未存儲任何id,因此它們將被設置爲0,1,...因此$ authors [0]將與第一次迭代中的$ author相同。 – 2012-03-13 19:08:17

+0

@Ben不,輸出肯定是1-1 2-2。 – renard 2012-03-13 19:15:40

回答

1

爲什麼$ authors [0] - > id引用$ author-> id ??

它不是(在第一次迭代之後)。

有什麼不對其他地方(也許在Author::__constructAuthor::manager):

class Author 
{ 
    public $id; 

    function __construct($params) 
    { 
     $this->id = substr($params['last_name'], -1); 
    } 
} 


$authors = array(                                       
    new Author(array('first_name'=>'Name 1','last_name'=>'last name 1')),                           
    new Author(array('first_name'=>'name 1','last_name'=>'last name 2')),                         
);                                           

foreach($authors as $key => $author){                                                                  
    print $author->id."-".$authors[0]->id."<br>";                                                                
} 

/* 
output: 

1-1 
2-1 

*/ 
+0

的確,有一個ORM層執行查詢來創建或獲取數據。然後我檢索了帶有陰影數據(例如id屬性)的PHP對象模型。 – renard 2012-03-13 19:19:32