2012-03-13 66 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