Inherited PHP array properties

I have a class hierarchy in PHP 5.2.9 .

The base class has a protected property, which is an associative array.

Children's classes can add some elements to the array.

Children's classes are declared in separate files (plugins), which will be created and added by several developers.

What is the best way to add elements to a property in child classes so that declaring a new child is as simple as possible?

 <?php class A { protected $myproperty = array ( 'A1' => 1, 'A2' => 2 ); function myprint() { print_r($this->myproperty); } }; class B extends A { // add 'B1', 'B2' to myproperty }; class C extends B { // add 'C1', 'C2' to myproperty }; $c = new C(); $c->myprint(); // The line above should print A1, A2, B1, B2, C1, C2 ?> 

Ideally, I would like to do this for developers as simple as declaring a variable or private property without having to copy paste any code.

+4
source share
1 answer

Use the constructors of inherited classes, for class B it will be something like this:

 class B extends A { function __construct() { parent::__construct(); // Call constructor of parent class array_push($myproperty, "B1", "B2"); // Add our properties } } 

The same applies to class C.

If you have many inherited classes or want to provide as much support as possible, you can put this code in some function. Therefore, other developers only need to call this function in their constructor in order to "register" their child.

+3
source

Source: https://habr.com/ru/post/1298988/


All Articles