如何在抽象类的构造函数中设置默认值?

我有一个抽象类,其中包含这样的 __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']);


POPMUISE
浏览 76回答 1
1回答

牛魔王的故事

尝试一下:我做了$attributes public, 来显示结果。注意问号??。<?phpclass 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);
打开App,查看更多内容
随时随地看视频慕课网APP