N
N
Nurlan2018-03-21 12:39:05
PHP
Nurlan, 2018-03-21 12:39:05

How to create a previously unknown instance of a class?

Is there some correct principle for writing / building code for a situation where you need to create an instance of a class, but we don’t know in advance what kind of class we need.
For example:
There is a banner, the array stores targeting options ['geo','date','etc'] and there are classes that implement checks of these targetings.
Option

foreach($banner['target'] as $target){
$obj=new $target();
$obj->check();
}

It seems to me not very beautiful and true, but maybe it's just speculation.
Situations like this don't happen often, but they do happen. Interested in the opinion of more experienced.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Tallmange, 2018-03-21
@daager

Factory with sample code in many languages

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question