...

View Full Version : & symbols



missing-score
11-02-2003, 05:55 PM
ok, ive seen code examples like:




$var = &new class();



what does the & do? ive seen it used other places too... i looked on php.net, but couldnt find anything via search.

mordred
11-02-2003, 10:40 PM
The "&" symbol is used to assign a reference to the variable, instead of a copy. Here's a sample that illustrate the underlying problem:



class Book {
var $_author = '';

function Book($author) {
$this->_author = (string) $author;
}

function getAuthor() {
return $this->_author;
}

function setAuthor($author) {
$this->_author = (string) $author;
}
}

$redBook = new Book('Bob');
var_dump($redBook->getAuthor());

$blueBook = $redBook;
$blueBook->setAuthor('Joe');

var_dump($redBook->getAuthor());


The first dump prints "Bob", as expected. But what prints the second dump? It's exactly the same statement, only that some lines before we assigned $redBook to $blueBook, and change the author of $blueBook. But $blueBook is the same as $redBook, so shouldn't that change the author of $redBook underneatch, because they all refer to the same object? Nope. PHP has a very nasty characterisc of creating copies of objects when they are assigned to another variable. So the last dump prints "Bob" again, because the change to the book's author was made on a copy of the object, not the object itself.

But most of the time you rather want a reference, and that's why there is this & symbol to force the assignment of a reference. You can read more about references in PHP here:
http://www.php.net/manual/en/language.references.php

missing-score
11-03-2003, 07:33 AM
i see :), thanks :thumbsup:



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum