Can PHP instantiate an object from the name of the

2019-01-31 11:07发布

Is it possible in PHP to instantiate an object from the name of a class, if the class name is stored in a string?

4条回答
疯言疯语
2楼-- · 2019-01-31 11:24

Static too:

$class = 'foo';
return $class::getId();
查看更多
别忘想泡老子
3楼-- · 2019-01-31 11:31

Yep, definitely.

$className = 'MyClass';
$object = new $className; 
查看更多
We Are One
4楼-- · 2019-01-31 11:46

Yes it is:

<?php

$type = 'cc';
$obj = new $type; // outputs "hi!"

class cc {
    function __construct() {
        echo 'hi!';
    }
}

?>
查看更多
SAY GOODBYE
5楼-- · 2019-01-31 11:50

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.

查看更多
登录 后发表回答