Im currently getting my hands dirty with some subclassing object oriented php. I would like to use an array to create some form fields, and these fields are separated into classes based on their type. This means that I have a main class called "form_field", and then have a bunch of subclasses called "form_field_type" (ex. "form_field_select"). The idea is that each subclass "knows" how to best generate their HTML in a display method.
So lets say that i write an array like this:
$fields = array(
array(
'name' => 'field1',
'type' => 'text',
'label' => 'label1',
'description' => 'desc1',
'required' => true,
),
array(
'name' => 'field2',
'type' => 'select',
'label' => 'label1',
'description' => 'desc1',
'options' => array(
'option1' => 'Cat',
'option2' => 'Dog',
),
'ui' => 'select2',
'allow_null' => false,
)
);
I would then like to create a loop that instantiates the correct class based on the type:
foreach ($fields as $field) {
$type = $field['type'];
$new_field = // instantiate the correct field class here based on type
$new_field->display();
}
What would be the best approach here? I would like to avoid doing something like:
if ($type == 'text') {
$new_field = new form_field_text();
} else if ($type == 'select') {
$new_field = new form_field_select();
} // etc...
This just feels inefficient, and i feel like there must be a better way? Is there a good pattern that is generally used in this situation, or am I going about solving this the wrong way?