Page 1 of 1

This : "&"

Posted: Sat Jul 28, 2007 9:18 am
by abalfazl
Hello
From:php|architect’s Guide to PHP Design Patterns

Sample Code
The Factory pattern encapsulates the creation of objects. You can create a Factory within the object
itself or in an external Factory class—the exact implementation depends on the needs of your application.
Let’s look at an example of a Factory.
The application code below repeats the same code to create a database connection in multiple
places:
// PHP4
class Product {
function getList() { $db =& new MysqlConnection(DB_USER, DB_PW, DB_NAME);
//...
}
function getByName($name) { $db =& new MysqlConnection(DB_USER, DB_PW, DB_NAME);
//...
}
//...
}




[/b]
Why does he use this " &" in this code?
$db =& new MysqlConnection(DB_USER, DB_PW, DB_NAME);

Thanks

Posted: Sat Jul 28, 2007 9:40 am
by superdezign
The ampersand forces PHP to send a reference to the object that is being created by the factory pattern instead of a copy in order to save memory.

The need to use that is officially deprecated as of PHP 5, and is only for use in PHP 4. PHP 5 automatically sends references of objects, one of the many reasons to Go PHP5.

Posted: Sat Jul 28, 2007 9:40 pm
by califdon
superdezign wrote: one of the many reasons to Go PHP5.
Yeah, tell that to my shared hosting provider! 8O

Posted: Sun Jul 29, 2007 8:25 am
by superdezign
califdon wrote:
superdezign wrote: one of the many reasons to Go PHP5.
Yeah, tell that to my shared hosting provider! 8O
Hehe, beware. My host added a PHP5 server, and then turned register_globals on AND magic_quotes! Bastards.

I convinced them of the insecurities of register_globals and they disabled it, but the best I could come up for magic_quotes is that they are annoying and promote lazy programmers and bad practice. Their defense was that it prevents SQL injection by newer programmers.

I figure since they'll be gone in PHP 6, you'd realize that it's a bad idea and the programmers will need to get used to living without it anyway... Oh well.