Can PHP instantiate an object from the name of the class as a string?

PhpClassObjectInitialization

Php 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

Yes it is:

<?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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser135295View Question on Stackoverflow
Solution 1 - PhpbrianreavisView Answer on Stackoverflow
Solution 2 - PhpjosefView Answer on Stackoverflow
Solution 3 - PhpMr. SmithView Answer on Stackoverflow
Solution 4 - PhpAndrew AtkinsonView Answer on Stackoverflow
Solution 5 - PhpHugo RView Answer on Stackoverflow