I have doubt about how to set variable in __construct
I have some controllers, each controller has a js file, so when I used Yii 1, I created a variable in construct and to set a address to js, I do this:
class MyController extends Controller{
public $scriptJS;
public function __construct($id) {
parent::$this->scriptJS = array(Yii::app()->request->baseUrl . "/libs/myjs/myjs.js");
parent::__construct($id);
}
..
}
After put this code in construct I put this code in my default layout:
<?php if (isset($this->scriptJS) AND !empty($this->scriptJS)): ?>
<?php foreach ($this->scriptJS as $script) : ?>
<script src="<?= $script ?>"></script>
<?php endforeach; ?>
<?php endif; ?>
This way each controller load the specific js, I’m trying do this in Yii 2, I created this construct:
public $scriptJS;
public function __construct($id, $module, $config = []) {
$this->id = $id;
$this->module = $module;
$this->scriptJS = array("/libs/myjs/myjs.js");
parent::__construct($id, $module, $config = []);
}
And in my default layout I put the same code:
<?php if (isset($this->scriptJS) AND !empty($this->scriptJS)): ?>
<?php foreach ($this->scriptJS as $script) : ?>
<script src="<?= $script ?>"></script>
<?php endforeach; ?>
<?php endif; ?>
But don’t load the variable scriptJS. Where I’m wrong?
Yii2 is not backwards compatible with 1.x. The good news is that what you want to do is now simpler, you could achieve the same thing in a constructor or init method with:
1. in /Users/Alexandre/web_projects/ibless/medicine_work/vendor/yiisoft/yii2/base/Component.php at line 282
273274275276277278279280281282283284285286287288289290291
*/
public function __call($name, $params)
{
$this->ensureBehaviors();
foreach ($this->_behaviors as $object) {
if ($object->hasMethod($name)) {
return call_user_func_array([$object, $name], $params);
}
}
throw new UnknownMethodException('Calling unknown method: ' . get_class($this) . "::$name()");
}
/**
* This method is called after the object is created by cloning an existing one.
* It removes all behaviors because they are attached to the old object.
*/
public function __clone()
{
$this->_events = [];