我有一个抽象类,其中包含这样的 __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 关注
- 120 浏览
添加回答
举报
0/150
提交
取消