[英]PHP foreach loop odd references behaviour
我有一个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循环中使用引用,所以我不知道它从何而来!
任何建议都将受到欢迎。 谢谢
为什么$ authors [0]-> id指向$ author-> id?
没有 (在第一次迭代之后)。
其他地方出了点问题(也许在Author::__construct
或Author::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
*/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.