通过引用传递而不是使用全局传递的优势? [英] Advantage of passing by reference opposed to using global?

查看:63
本文介绍了通过引用传递而不是使用全局传递的优势?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究MVC模式,我可以在上看到一个示例phppatterns 他们通过引用传递模型-这样做比全局变量有什么好处?我缺少明显的东西吗?

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. 他们认为只有模型和视图的一种实现.
  2. 他们假设模型和视图只有一个实例(您的应用程序中可以有多个实例).
  3. 它们隐藏了组件之间的相互依赖关系;您的视图受模型的影响很大,但是不必显式地将模型传递到视图中就可以做到这一点.

出于其他原因,为什么全局变量和单例是邪恶的"(即,实际上是您永远不应该做出的糟糕的设计决定),请阅读

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.

这篇关于通过引用传递而不是使用全局传递的优势?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆