我有一個抽象類,其中包含這樣的 __construct 方法abstract class Model{ protected $attributes = []; public function __construct(array $attributes = []) { $this->$attributes = $attributes; }}然后在我的具體類中我擴展了抽象模型class Pong extends Model{ }當我轉儲構造函數內的屬性時,我得到一個空數組,但如果刪除構造函數參數的默認值,Pong 模型就有屬性。挑戰是,我希望能夠使用默認值和不使用默認值來構造具體類$pong = new Pong();$pong = new Pong(['msg' => 'Hello Kitty']);
1 回答

牛魔王的故事
TA貢獻1830條經驗 獲得超3個贊
嘗試一下:
我做了$attributes public, 來顯示結果。
注意問號??。
<?php
class Model
{
? ? public $attributes = [];
? ? public function __construct(array $attr = []) {
? ? ? ? $this->attributes['msg'] = $attr['msg'] ?? "default";
? ? ? ? $this->attributes['someValue'] = $attr['someValue'] ?? 'default';
? ? }
}
class Pong extends Model
{
? ??
}
$pong = new Pong();
print_r($pong->attributes);
- 1 回答
- 0 關注
- 148 瀏覽
添加回答
舉報
0/150
提交
取消