Create a custom widget with constructor:
class MyWidget extends \yii\base\Widget {
public function __construct($a, $b, array $config = []) {
}
}
And use in view:
MyWidget::begin(); // DI will throw
MyWidget::widget(); // DI will throw
Should support set construct params:
MyWidget::widget([], [1, 2]);
| Q | A
| ---------------- | ---
| Yii version | 2.0.15
| PHP version | 7.1
| Operating system | Windows
Why do you want to make $a and $b a constructor parameters instead configuring them by $config array?
For some special case like:
class MyWidget extends \yii\base\Widget {
public $a = 0;
private $_b;
public function setB($b) {
// this need property a to do something
$this->_b = $this->a + $b;
}
}
Now we must take care a position of properties in an array config:
// b will be 123
MyWidget::widget([
'b' => 123,
'a' => 1
]);
// b will be 124
MyWidget::widget([
'a' => 1
'b' => 123,
]);
You should be able to do this in init()?
How if it more complex like:
class MyWidget extends \yii\base\Widget {
private $_a;
public function getA() {
return $this->_a;
}
public function setA($value){
$view = $this->getView();
}
}
setter A need view and view will be an object Yii::$app->view but i need use my custom view
MyWidget::widget([
'a' => 123, // `view` instance in `setA` will be `Yii::$app->view`
'view' => $myView
]);
MyWidget::widget([
'view' => $myView,
'a' => 123, // `view` instance in `setA` will be `myView`
]);
Your setA() method does not make any sense. Can you give some real use case?
create new method with setXXX
and init widget as WidgetClass::widget(['XXX' => '']);
clear and simple