I am working on an extremely old project that has migrated from PHP 4 to PHP 5.2 and we are now migrating the project to PHP 5.4. We've come up with a number of reference errors. Here is some example code that's bugging me.
<?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();
?>
I would expect this to create 3 separate books. But instead every object in the elements array ends up pointing to the last variable. On the other hand if I create a new book by reference everything works right. (e.g. $book1 =& new book("Book $i");
) Here is the example code:
<?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();
I was under the impression that creating an object by reference in PHP 5.4 was not necessary. Any idea why I am getting different results?