从Yii2中组件的配置中获取值
如何访问组件中组件的配置值 config/main.php 如何访问组件中的从Yii2中组件的配置中获取值,yii2,Yii2,如何访问组件中组件的配置值 config/main.php 如何访问组件中的someValue 我试图在类中声明变量public$someValue,但它不是自动填充的 编辑: 以下是我的组件: namespace common\components; use Yii; use yii\base\Component; class myComponent extends Component { public function init() { parent::i
someValue
我试图在类中声明变量public$someValue
,但它不是自动填充的
编辑:
以下是我的组件:
namespace common\components;
use Yii;
use yii\base\Component;
class myComponent extends Component
{
public function init()
{
parent::init();
}
public $someValue;
public function getSomeValue()
{
return $someValue
}
}
根据,您可以在创建自己的组件时重写\u construct()
方法
然后可以按如下方式设置特性值:
public function __construct($config = [])
{
parent::__construct($config);
}
同样,在您的方法
getSomeValue()
中,您需要返回$this->someValue
,而不是$someValue
,事实上您就快到了。。。这个问题使我找到了答案
组件中定义的key=>值(即'myConfigValue'=>'someValue')
将映射到组件类的属性。
注意,没有映射到b的属性的键将抛出错误
class () ...
public $version = null;
public function __construct($config = [])
{
// ... initialization before configuration is applied
$this->config = $config;
// use reflection
// will map $config keys to attributes
// e.g. 'version' => 1 mapped to $this->version
parent::__construct($config);
}
不能对bublic属性使用params您只能访问组件的公共属性,或者需要对其进行扩展并添加您的属性和方法。t是否可以添加
common\components\MyComponent
的代码?当然可以。。还不多,我等会儿再试试。感谢you@Jørgen对你有用吗?如果是,请接受答案:)
class () ...
public $version = null;
public function __construct($config = [])
{
// ... initialization before configuration is applied
$this->config = $config;
// use reflection
// will map $config keys to attributes
// e.g. 'version' => 1 mapped to $this->version
parent::__construct($config);
}