I have the following classes:

<?php class Person extends Academy { public $name; public function __construct($name) { $this->name = $name; } public function ShowData() { return ['name' => $this->name]; } } class Student extends Person { public $education; public function __construct($name, $education) { parent::__construct($name); $this->education = $education; } public function showData() { return array_merge(parent::showData(), [ 'education' => $this->education ]); } } class Worker extends Person{ public $workPlace; public function __construct($name, $workPlace) { parent::__construct($name); $this->workPlace = $workPlace; } public function showData() { return array_merge(parent::showData(), [ 'workPlace' => $this->workPlace ]); } } ?> 

And their parent class:

 <?php class Academy { private $items = array(); public function showAll($key) { … } public function addPerson($obj, $key = null) { … } } ?> 

I need to implement the showAll (shows Name, Education, and WorkPlace for all people) and addPerson (adds a new person to the Academy). I understand that derived classes have a showDate method and the showAll method can get data with it, but I do not know how to implement it.

  • What is the meaning of $key ? - vp_arth
  • you are right, probably the parameter is useless here - Marian Hryntsiv

2 answers 2

It seems simple:

 class Academy { private $items = array(); public function showAll() { return array_map(function($person){ return $person->showData(); }, $this->items); } public function addPerson(Person $person) { $this->items[] = $person; } } 

And remove extends Academy from Person . This is no good.
Academy is a collection class, they have not a hierarchical relationship, but a compositional one.

    You are trying to apply method polymorphism, which is not supported in PHP. Even in C ++, for everything to work beautifully, you need to declare the methods virtual, and there are no such words in PHP. Something like polymorphism can be implemented through interfaces - in your case, for example:

     interface DataShowinist { public function showData(); } 

    Then each class

     class Person extends Academy implements DataShowinist { ... 

    And finally:

     public function addPerson(DataShowinist $obj, $key = null) { ... $obj.showData(); } 

    But there is no virtual method table in PHP; accordingly, there is no interest in creating a class hierarchy either.

    • In php, all methods are virtual. - vp_arth
    • I would call it rather "redefinable", that is, yes, the method can be overridden during inheritance, but the information on the implementation of the parent method will be completely lost - Eugene Bartosh
    • Why would it suddenly? There is a call to the parent method, there is a later static binding. You about some unknown php - vp_arth to me