在PHP中基于字符串动态实例化类


Dynamically instantiating a class based on string in PHP

我目前正忙于一些面向对象php的子类化。我想使用一个数组来创建一些表单字段,这些字段根据其类型划分为类。这意味着我有一个名为"form_field"的主类,然后有一堆名为"form_field_type"的子类(例如"form_field_select")。这个想法是每个子类都"知道"如何在显示方法中最好地生成它们的HTML。

比方说,我写了一个这样的数组:

$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,
    )
);

然后我想创建一个循环,根据类型实例化正确的类:

foreach ($fields as $field) {
    $type = $field['type'];
    $new_field = // instantiate the correct field class here based on type
    $new_field->display();
}

这里最好的方法是什么?我想避免做这样的事情:

if ($type == 'text') {
    $new_field = new form_field_text();
} else if ($type == 'select') {
    $new_field = new form_field_select();
} // etc...

这感觉效率很低,我觉得一定有更好的方法吗?有没有一个好的模式通常用于这种情况,或者我会以错误的方式解决这个问题?

试试这样的。。。

foreach ($fields as $field) {
    $type = $field['type'];
    // instantiate the correct field class here based on type
    $classname = 'form_field_' .$type;
    if (!class_exists($classname)) { //continue or throw new Exception }
    // functional
    $new_field = new $classname();
    // object oriented
    $class = new ReflectionClass($classname);
    $new_field = $class->newInstance();
    $new_field->display();
}