PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
In the examples/articles related to OOP I find the second case more often. Would like someone to explain me this. I do undertand what a reference is, but I don't understand why would I want to initially create a reference to a new class instance. So far, I've always used
in some instances (versions) of php, the object is copied to the variable, not automatically referenced. The ampersand explicitly tells PHP to store and use the reference. At least, that's what I've read in various locations.. I do it because I think it's good practice, and if php was going to use the reference anyways, it doesn't really hurt anything
If I want an object, I use $object = new Object(). That means that I just got a new instance of the class Object in the variable $object, in short I just got an object. If I want to create a reference to that object, I could then do $ref = &$object, so in this case I would have the object itself ($object) and the reference to it ($ref).
Now where does $object = &new Object() come to play? Why do I need it at all? I even don't understand exactly what that means. If $object is a reference, then... what is it reference to? How can I access the thing which $object is the reference to? And overall, what's wrong with $object = new Object()?
The use of &, the reference operator might look quite strange to guys who have come from C++ and other OO langs as it appeared to me first.
It happens like this,
when you say new Object();, a memory block is allocated with a starting memory location and usually the object, object here is given the physical name for the memory location or atleast it points to that location.
As you may infer from feyd, the object gets created and a copy of that object is made and allocated when object - new Object();
when you use &new Object(), I think no copy of the object is made instead the first created object is used.