Advantage of passing by reference opposed to using

2019-02-25 04:22发布

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
   }
}

6条回答
孤傲高冷的网名
2楼-- · 2019-02-25 04:54

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

查看更多
Explosion°爆炸
3楼-- · 2019-02-25 04:54

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楼-- · 2019-02-25 05:04

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.

查看更多
Emotional °昔
5楼-- · 2019-02-25 05:04

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.

查看更多
唯我独甜
6楼-- · 2019-02-25 05:10

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.

查看更多
男人必须洒脱
7楼-- · 2019-02-25 05:19

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

查看更多
登录 后发表回答