简体   繁体   English

在PHP的子类中修改父公共变量

[英]Modifying parent public variable in child class in PHP

Is it somehow possible to modify parent public var which is an array so that in child class it will have more items in it? 是否可以以某种方式修改作为数组的父公共变量,以便在子类中将包含更多项?

For now i'm just repeating parent array physically and then adding some items to it: 现在,我只是在物理上重复父数组,然后向其中添加一些项目:

class A {
    public $arr = ['hello'];
}

class B extends A {
    public $arr = ['hello','world']; //wanna get rid of 'hello' and use parent
}

The field declaration should be named $arr , not arr . 字段声明应命名为$arr ,而不是arr And, you shouldn't re-declare the same field in the child class. 并且,您不应在子类中重新声明相同的字段。 You can change it in the constructor: 您可以在构造函数中进行更改:

class A {
    public $arr = ['hello'];
}

class B extends A {
    public function __construct() {
        $this->arr []= 'world';
    }
}

A small test: 一个小测试:

$a = new A(); print_r( $a->arr );
$b = new B(); print_r( $b->arr );

produces: 生产:

Array
(
    [0] => hello
)
Array
(
    [0] => hello
    [1] => world
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM