Yii2构造函数中缺少必需的参数
我已经创建了一个新的Yii2构造函数中缺少必需的参数,yii2,Yii2,我已经创建了一个新的xmlresponseformter,现在我想更改rootTag class newXmlResponseFormatter extends XmlResponseFormatter { /** * @var string the name of the root element. * */ public $rootTag; public function __construct($rootTag) {
xmlresponseformter
,现在我想更改rootTag
class newXmlResponseFormatter extends XmlResponseFormatter
{
/**
* @var string the name of the root element.
*
*/
public $rootTag;
public function __construct($rootTag) {
parent::__construct();
$this->rootTag = $rootTag;
}
}
我通过控制器设置该值:
$xmlFormater = new newXmlResponseFormatter('newRootTag');
在控制器中,该值可用,并在$rootTag中设置,但引发了以下异常:
异常“yii\base\InvalidConfigException”,在/var/www/html/Admin/vendor/yiisoft/yii2/di/Container.php:451中实例化“app\components\override\newXmlResponseFormatter.”时显示消息“缺少所需参数“rootTag”
有人知道什么是问题吗?
提前谢谢 XMLResponseFormat中的第一个参数是
$config
,因为XMLResponseFormat
扩展了对象
类。你是
您应该像这样重写构造函数:
class newXmlResponseFormatter extends XmlResponseFormatter
{
/**
* @var string the name of the root element.
*
*/
public $rootTag;
/**
* newXmlResponseFormatter constructor.
*
* @param string $rootTag
* @param array $config
*/
public function __construct($rootTag, $config = [])
{
$this->rootTag = $rootTag;
parent::__construct($config);
}
}
new newXmlResponseFormatter(['rootTag' => 'newRootTag']);
在yii2中,您应该在代码之后调用父构造函数,在代码之前调用父构造函数
$config
需要这样简单的配置模型:
class newXmlResponseFormatter extends XmlResponseFormatter
{
/**
* @var string the name of the root element.
*
*/
public $rootTag;
/**
* newXmlResponseFormatter constructor.
*
* @param string $rootTag
* @param array $config
*/
public function __construct($rootTag, $config = [])
{
$this->rootTag = $rootTag;
parent::__construct($config);
}
}
new newXmlResponseFormatter(['rootTag' => 'newRootTag']);
我按照你说的做了:
code
classnewxmlresponseformter扩展了xmlresponseformter{/***@var string根元素的名称。**/public$rootTag;public function uu构造($rootTag,$config=[]){parent::init()$this->rootTag=$rootTag;父项::_构造($config);}code
Controller:code
$xmlformatter=newXmlResponseFormatter('newRootTag',[])code
但是,我仍然有相同的错误,异常…应该在单个init
函数中的构造函数之后调用父init
。从构造函数中删除它,它就会工作:)仍然不工作:(code
public function\uuu-construct($rootTag,$config=[]){$this->rootTag=$rootTag;parent::\uu-construct($config);}公共函数init(){parent::init()}code
尝试删除constructor、init并使用它:newxmlresponseformter(['rootTag'=>'newRootTag']);
然后,我可以从我的控制器动态更改该值:$response->formatters['xml']['rootTag']=“newValue”;