我正在处理一个非常古老的项目,该项目已从 PHP 4 迁移到 PHP 5.2,我们现在正在将该项目迁移到 PHP 5.4。我们提出了许多参考错误。这是一些困扰我的示例代码。
<?php
class book_shelf
{
protected $_elements = array();
function addBook(&$element){
$this->_elements[] =& $element;
}
function printBooks(){
print(json_encode($this->_elements));
}
}
class book
{
function __construct($title, $author="unknown") {
$this->title = $title;
$this->author = $author;
}
public $title = NULL;
public $author = NULL;
}
function createBookShelf(){
$bookshelf1 = new book_shelf();
for ($i = 0; $i < 3; $i++){
$book1 = new book("Book $i");
$bookshelf1->addBook($book1);
}
$bookshelf1->printBooks();
}
createBookShelf();
?>
我希望这可以创建 3 本书。但是元素数组中的每个对象最终都指向最后一个变量。另一方面,如果我通过引用创建一本新书,一切正常。(例如$book1 =& new book("Book $i");
)这是示例代码:
<?php
class book_shelf
{
protected $_elements = array();
function addBook(&$element) {
$this->_elements[] =& $element;
}
function printBooks(){
print(json_encode($this->_elements));
}
}
class book
{
function __construct($title, $author="unknown") {
$this->title = $title;
$this->author = $author;
}
public $title = NULL;
public $author = NULL;
}
function createBookShelf() {
$bookshelf1 = new book_shelf();
for ($i = 0; $i < 3; $i++){
$book1 =& new book("Book $i");
$bookshelf1->addBook($book1);
}
$bookshelf1->printBooks();
}
createBookShelf();
我的印象是在 PHP 5.4 中通过引用创建对象是不必要的。知道为什么我会得到不同的结果吗?