【问题标题】:Dynamically instantiating a class based on string in PHPPHP中基于字符串动态实例化类
【发布时间】:2014-11-15 14:29:04
【问题描述】:

我目前正在使用一些面向对象的子类化 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...

这只是感觉效率低下,我觉得必须有更好的方法?在这种情况下是否有一个很好的模式,或者我打算以错误的方式解决这个问题?

【问题讨论】:

标签: php oop dynamic instance subclass


【解决方案1】:

试试这样的...

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();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-03
    • 1970-01-01
    • 1970-01-01
    • 2021-06-25
    • 2011-01-13
    • 2021-04-18
    • 1970-01-01
    相关资源
    最近更新 更多