PHP 是否可以从类的名称实例化一个对象作为字符串?

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

38312 次浏览

Yep, definitely.

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

Yes it is:

<?php


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


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


?>

Static too:

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

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.

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));