如何使用参数在 yii2 中构造或初始化 activerecord 对象?
how to construct or initialize an activerecord object in yii2 with arguments?
假设我想使用一些参数构造一个 "player" activerecord 对象。如何传递参数?一些文章建议不要覆盖 __construct 方法,而是使用应该在构造方法末尾内部调用的 init() 函数。但是如何传递参数来初始化对象呢?
如果我将参数传递给构造函数,它会抱怨我:
Declaration of app\models\Player::init(app\models\Game $game) should
be compatible with yii\db\BaseActiveRecord::init()
代码如下所示:
控制器:
$game = Game::findOne($id);
$player = new Player($game);
型号:
public function init(Game $game) {
$this->game_id = $game->id;
}
扩展 BaseObject
的每个对象都可以使用 $config
parameter in the __construct()
method.
初始化对象
例如:您可以通过传递带有对象 属性 参数的数组来构造 Player
或 Game
对象,例如 $game = new Game(['player_id' => 1])
.
假设我想使用一些参数构造一个 "player" activerecord 对象。如何传递参数?一些文章建议不要覆盖 __construct 方法,而是使用应该在构造方法末尾内部调用的 init() 函数。但是如何传递参数来初始化对象呢? 如果我将参数传递给构造函数,它会抱怨我:
Declaration of app\models\Player::init(app\models\Game $game) should be compatible with yii\db\BaseActiveRecord::init()
代码如下所示:
控制器:
$game = Game::findOne($id);
$player = new Player($game);
型号:
public function init(Game $game) {
$this->game_id = $game->id;
}
扩展 BaseObject
的每个对象都可以使用 $config
parameter in the __construct()
method.
例如:您可以通过传递带有对象 属性 参数的数组来构造 Player
或 Game
对象,例如 $game = new Game(['player_id' => 1])
.