首页 > 解决方案 > 如何在抽象类的构造函数中设置默认值?

问题描述

我有一个包含这样的 __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']);

标签: php

解决方案


试试这个:

我做了$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);

使用您在上面看到的代码


推荐阅读