The advantage of following a link versus using a global one?

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

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 you do this as shown by 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
   }
}
+3
source share
6 answers

The problem with global variables is this:

  • They suggest that there is only one implementation of the model and view.
  • They assume that there is only one instance of the model and view (you may have several of them in your application).
  • ; , , .

, "" (.. , ), , .

+4

- , .

+3

, , , , PHP 5. , , !

, , PHP 5 :

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
+2

(), , , , . , , , .

+1

, , .

0

, , . , , , , , PHP 4. PHP 5 .

0

Source: https://habr.com/ru/post/1759822/


All Articles