dynamic class names in php

前端 未结 7 1607
-上瘾入骨i
-上瘾入骨i 2020-12-07 00:31

I have a base class called field and classes that extend this class such as text, select, radio, checkbox, <

相关标签:
7条回答
  • 2020-12-07 00:51

    This should be enough:

    $field_type = 'checkbox';
    $field = new $field_type();
    

    Code I tested it with in PHP 5.3

    $c = 'stdClass';
    
    $a = new $c();
    
    var_dump($a);
    
    >> object(stdClass)#1 (0) {
    }
    
    0 讨论(0)
  • 2020-12-07 00:55

    This should work to instantiate a class with a string variable value:

    $type = 'Checkbox'; 
    $field = new $type();
    echo get_class($field); // Output: Checkbox
    

    So your code should work I'd imagine. What is your question again?

    If you want to make a class that includes all extended classes then that is not possible. That's not how classes work in PHP.

    0 讨论(0)
  • 2020-12-07 00:57

    If you are using a namespace you will need to add it even if you are within the namespace.

    namespace Foo;
    
    $my_var = '\Foo\Bar';
    new $my_var;
    

    Otherwise it will not be able to get the class.

    0 讨论(0)
  • 2020-12-07 00:59

    You can also use reflection, $class = new ReflectionClass($class_name); $instance = $class->newInstance(arg1, arg2, ...);

    0 讨论(0)
  • 2020-12-07 01:03

    just

    $type = 'checkbox';
    $filed = new $type();
    

    is required. you do not need to add brackets

    0 讨论(0)
  • 2020-12-07 01:04
    $field_type = 'checkbox';
    $field = new $field_type;
    

    If you need arguments:

    $field_type = 'checkbox';
    $field = new $field_type(5,7,$user);
    
    0 讨论(0)
提交回复
热议问题