Advantage of passing by reference opposed to using

2019-02-25 04:19发布

问题:

im looking at the MVC pattern, and I can see in one example on phppatterns they're passing the model by reference - any benefit of doing this over a global var? Am I missing something obvious?

class MyView extends View {
  var $model; 

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

  function productTable($rownum=1) {
    $rowsperpage='20';
    $this->model->listProducts($rownum,$rowsperpage);
    while ( $product=$this->model->getProduct() ) {
         // Bind data to HTML
    }
  }
}

Any reason why you would do this as apposed to using a global variable? i.e.

class MyView extends View {
  global $model;

  function __construct(){ }

  function productTable($rownum=1) {
    $rowsperpage='20';
    $model->listProducts($rownum,$rowsperpage);
    while ( $product=$this->model->getProduct() ) {
         // Bind data to HTML
   }
}

回答1:

The problem with global variables is that:

  1. They assume that there is only one implementation of model and view.
  2. They assume that there is only one instance of the model and view (you could have several of each in your application).
  3. They hide the interdependency between components; your view is very strongly affected by the model, but not having to explicitly pass a model into your view makes this implicit.

For other reasons why globals and singletons are "evil" (i.e. just really a poor design decision that you should never make), read avoid global variables, environment variables, and singletons.



回答2:

Yes -- the advantage is that you could change the implementation of the model without having to modify the View.



回答3:

I'd suggest to use another tutorial, the one you're using is a bit outdated, and isn't PHP 5. That said, you really shouldn't use global variables, that's never the solution!

But I don't really get why you should even wanna pass it by reference, in PHP 5 it's already passed by reference:

class foo {
    public $a;
    public function __construct($a) {
        $this->a = $a;
    }
}

$a = new foo(10);
$b = $a;

$a->a = 20;

echo $a->a.' => '.$b->a; // 20 => 20


回答4:

If you have multiple (similar) model instances, on which you possibly would like to apply the same view, you would need to explicitly pass the model instance. A global variable assumes there could be only one model instance, and thus creates an artificial limitation.



回答5:

In general not using global variables is better to help you control the scope of your variables.



回答6:

I won't mention about why that is a bad thing, because it has been already discussed. One thing that I think you should know is that the code provided there is PHP 4 compatible. In PHP 5 by default objects are sent by reference.