How can I dynamically change the class of an object from a parent method?

I have a class called Report. I have several classes that inherit from the report, ClientReport, ClientVisitReport ...

class Report { ... public function load($id) { ... } } class ClientReport extends Report { ... public function load($id) { parent::load($id); ... } } class ClientVisitReport extends Report { ... public function load($id) { parent::load($id); ... } } 

I want to be able to call the correct constructor from the identifier that I pass to the load method. Each identifier has its own report.

Basically I ask how can I do this:

 $reportObject = new Report(); // reportObject is a Report $reportObject->load(15678); // report 15678 is a ClientReport, $reportObject is now a ClientReport 

How can I do it? Maybe I'm wrong in my design, is there a better way to do what I want?

+4
source share
3 answers

You might want to explore the AbstractFactory pattern . One of his goals is

Provide an interface for creating families of related or dependent objects without specifying their specific classes.

There are PHP examples at the bottom of the linked page.

+4
source

Changing a class, the class of the object does not look like a good idea (maybe not even in most languages).

I would use a Prototype design template as well as a hash map to store report numbers / types.

So the code at the end will be:

 $reportObject = $reportTypes[15678]->clone(); 

For more information on examples and examples, see.

0
source

One of the ways that can help is to have the ReportLoader class in which you save the loading behavior and decide the type of report object you want to create. Thus, the report will be responsible for reporting, and Loader will load the correct data into the correct responsibility of the facility.

0
source

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


All Articles