简体   繁体   中英

Joomla: How to pass variables from the constructor in the model to the view?

Seems like this shouldn't be that hard but is giving me fits.

Have variables initialized in the model's __construct method.

Need to access them in the view.html.php and default.php files.

In my model:

$this->MyVar = 'somevalue';

In my view.html.php:

$model = $this->getModel('mymodelname');
print_r($model) //checking, yes - the model's being pulled in
$myvar = $model->__construct($this->MyVar);
echo $myvar; //empty

What am I doing wrong and how do I fix it?

Thanks!

=========================================

Solution:

$model = $this->getModel('mymodelname');
echo $model->MyVar; // returns the variable in the model

__construct() does not return any value, this is why $myvar remains null . If you want, you can read more about it here

According to the specification (in the link above) you should pass to __construct an associative array that could hold one or more of the following fields:

  • 'name'
  • 'state'
  • 'dbo'
  • 'table_path'

and according to what you say - you pass a parameter. Try:

$arr = array('name' => $this->MyVar);
$model->__construct($arr);

Why use construct at all after you have instantiated the model simply do like this:

$model = $this->getModel('mymodelname');
$model->MyVar = $myvar;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM