tags:

views:

49

answers:

1

when I was looking for some MVC framework, I got the website: http://www.phppatterns.com/docs/design/archive/model_view_controller_pattern

however, like the code listed there makes me confused about references. For example:

  $dao=& new DataAccess ('localhost','user','pass','dbname');
  $productModel=& new ProductModel($dao);

each instance it makes, it adds '&' before the new operator, what does it exactly mean? the reference to the instance? Actually, I removed all the '&' before all these kind of instances and the code still works perfectly.

Another, codes like :

 function ProductView (&$model) {
    $this->model=& $model;
 }

I really think it could be revised like:

function ProductView (&$model) {
    $this->model=$model;
}

Am I right? what's the differences between these two? Actually, like the MVC code example listed above? if you revise the code like I did, the code still works.

Then, I got this post somewhere else: http://schlueters.de/blog/archives/125-Do-not-use-PHP-references.html

does it make sense? any suggestions about this would be helpful.

+2  A: 

Prior to PHP version 5 objects were passed by value and you had to explicitly specify the ampersand to get the object by reference.*

In PHP 5+, all objects are passed by reference and thus using ampersand is redundant.

Furthermore, as of PHP 5.3.0, code like the above will generate a STRICT error of "Assigning the return value of new by reference is deprecated".

If you're curious about the historical use (PHP 4 or before) of "$o =& new Object()" code see php-by-reference (in particular, the accepted answer there provides a good explanation).

To summarise:

  • in PHP 5 or above, it makes no difference. The code will work as expected with no memory or other differences.

  • In PHP 5.3 you might get some STRICT notices complaining about this usage (assuming you have STRICT notices turned on).

  • In PHP 4.x (or earlier) this method was used to prevent unnecessary duplication of objects.

(*) Passing references around is a good thing - no need to create copies of objects when you only need the one instance.

catchdave
Just a note that explicit references function slightly differently to implicit object references in some edge cases. I've seen code fail because PHP 5's object referencing guessed something wrong - change it to an explicit reference and it worked again. Examples are hard to find, unfortunately.
staticsan
I haven't seen any of cases like that (nor heard of it). Too bad you don't have any test cases. I'd be very interested to see when/how that happens. Post it up here if you find it :)
catchdave