PHP可以将类的名称中的对象实例化为字符串吗?

时间:2009-09-04 03:21:46

标签: php class object initialization

如果类名存储在字符串中,PHP是否可以从类的名称实例化对象?

5 个答案:

答案 0 :(得分:113)

是的,当然。

$className = 'MyClass';
$object = new $className; 

答案 1 :(得分:5)

<强> Yes it is

<?php

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

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

?>

答案 2 :(得分:4)

如果您的班级需要参数,则应这样做:

class Foo 
{
   public function __construct($bar)
   {
      echo $bar; 
   }
}

$name = 'Foo';
$args = 'bar';
$ref = new ReflectionClass($name);
$obj = $ref->newInstanceArgs(array($args));

答案 3 :(得分:1)

静态:

$class = 'foo';
return $class::getId();

答案 4 :(得分:0)

您可以通过将类名/方法存储在数据库等存储中来进行动态调用。 假设该类对错误具有弹性。

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

等。 然后在您的代码中使用数据库返回的字符串来获取类和方法名称。您甚至可以为您的类存储SQL查询,如果达到您的想象,则可以自动化。

$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}();
}
}

我使用此方法创建REST Web服务。