如何在PHP中扩展父类中的数组?

时间:2014-05-11 09:27:52

标签: php arrays class oop

如何在PHP中扩展父类中的数组?

我有类似的东西

class ParentClass {
    $this->player = array(
        'class' => array(
            'basic' => array(
                'name'      => $data['name'],
                'image'     => $data['img']
            )
        )
    );
}

如何在不使用此数据删除父类中的数据的情况下扩展$ this->播放器数组

class ChildClass extends ParentClass {
    $this->player => array(
        'class' => array(
            'loadout'   => array(
                'primary'   => array(
                    'name'      => $data1['name'],
                    'type'      => $data1['type']
                )
            )
        )
    );
}

所以输出将是

    (
        'class' => array(
            'basic' => array(
                'name'      => $data['name'],
                'image'     => $data['img']
            ),
            'loadout'   => array(
                'primary'   => array(
                    'name'      => $data1['name'],
                    'type'      => $data1['type']
                )
            )
        )
    )

我试过这个

class ParentClass {
    public $player;

    public function __construct($class) {
        $this->player = array(
            'class' => array(
                'basic' => array(
                    'name'      => $data['name'],
                    'image'     => $data['img']
                )
            )
        );
    }
}

class ChildClass extends ParentClass {
    public function __construct($class) {

        parent::__construct($class);

        $this->player['class'] = array(
            'loadout'   => array(
                'primary'   => array(
                    'name'      => $data1['name'],
                    'type'      => $data1['type']
                )
            )
        );
    }

    public function getData() {
        return $this->player;
    }
}

但它只打印

    (
        'class' => array(
            'loadout'   => array(
                'primary'   => array(
                    'name'      => $data1['name'],
                    'type'      => $data1['type']
                )
            )
        )
    )

1 个答案:

答案 0 :(得分:1)

您的构造应如下所示:

public function __construct($class) {

    parent::__construct($class);

    $this->player['class']['loadout'] = 
       array(
           'primary'   => array(
               'name'      => $data1['name'],
               'type'      => $data1['type']
            )
      );

}

使用新数组覆盖class之前的代码。此代码将数组loadout的{​​{1}}设置为新数组。