I have a base class called field
and classes that extend this class such as text
, select
, radio
, checkbox
, <
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) {
}
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.
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.
You can also use reflection, $class = new ReflectionClass($class_name); $instance = $class->newInstance(arg1, arg2, ...);
just
$type = 'checkbox';
$filed = new $type();
is required. you do not need to add brackets
$field_type = 'checkbox';
$field = new $field_type;
If you need arguments:
$field_type = 'checkbox';
$field = new $field_type(5,7,$user);