Is it possible to organize such a structure in PHP, and if so, how.

Given 3 classes A, B and C.

class A { public $error = array(); public function errors() { foreach ($this->error as $err) { echo $err."<br>"; } } } class B extends class A { public function __construct { $this->error[] = "Ошибка 1"; } } class C extends class A { public function __construct { $this->error[] = "Ошибка 2"; } } $a = new A(); $b = new B(); $c = new C(); $a->errors(); 

How to do this (what needs to be changed in the code) so that the result of this script becomes:

 Ошибка 1 Ошибка 2 

    2 answers 2

     class A { public static $error = []; public static function errors() { return implode('<br/>', self::$error); } } class B extends A { public function __construct() { self::$error[] = "Ошибка 1"; } } class C extends A { public function __construct() { self::$error[] = "Ошибка 2"; } } $b = new B(); $c = new C(); echo A::errors(); // Ошибка 1 // Ошибка 2 
    • one
      $ a = new A () is not even needed - Jean-Claude
    • No, it does not solve the desired problem. It is necessary to do so that the methods of classes B and C work with the same instance of class A. - Finies
    • @Finies updated the answer - Kirill Korushkin 2:24 pm
    • I considered the option of using static properties and methods, as well as passing an instance of a class as a variable, but I wanted to find a more elegant solution. Still looking for) - Finies

    Just in case, I’ll let you know how I solved my problem (at the same time I rewrote it removing typos :). I had to resort to nested inheritance and work only with class C. This slightly changed the essence, but allowed working with one instance of class C, including A and B.

     class A { public $error = array(); public function errors() { foreach ($this->error as $err) { echo $err."<br>"; } } } class B extends A { public function __construct() { $this->error[] = "Ошибка 1"; } } class C extends B { public function __construct() { parent::__construct(); $this->error[] = "Ошибка 2"; } } $c = new C(); $c->errors();