Can PHP instantiate an object from the name of the class as a string?
PhpClassObjectInitializationPhp Problem Overview
Is it possible in PHP to instantiate an object from the name of a class, if the class name is stored in a string?
Php Solutions
Solution 1 - Php
Yep, definitely.
$className = 'MyClass';
$object = new $className;
Solution 2 - Php
if your class need arguments you should do this:
class Foo
{
public function __construct($bar)
{
echo $bar;
}
}
$name = 'Foo';
$args = 'bar';
$ref = new ReflectionClass($name);
$obj = $ref->newInstanceArgs(array($args));
Solution 3 - Php
<?php
$type = 'cc';
$obj = new $type; // outputs "hi!"
class cc {
function __construct() {
echo 'hi!';
}
}
?>
Solution 4 - Php
Static too:
$class = 'foo';
return $class::getId();
Solution 5 - Php
You can do some dynamic invocation by storing your classname(s) / methods in a storage such as a database. Assuming that the class is resilient for errors.
sample table my_table
classNameCol | methodNameCol | dynamic_sql
class1 | method1 | 'select * tablex where .... '
class1 | method2 | 'select * complex_query where .... '
class2 | method1 | empty use default implementation
etc.. Then in your code using the strings returned by the database for classes and methods names. you can even store sql queries for your classes, the level of automation if up to your imagination.
$myRecordSet = $wpdb->get_results('select * from my my_table')
if ($myRecordSet) {
foreach ($myRecordSet as $currentRecord) {
$obj = new $currentRecord->classNameCol;
$obj->sql_txt = $currentRecord->dynamic_sql;
$obj->{currentRecord->methodNameCol}();
}
}
I use this method to create REST web services.