简体   繁体   中英

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 . 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
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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