【发布时间】:2009-09-04 03:21:45
【问题描述】:
如果类名存储在字符串中,PHP 是否可以从类名实例化对象?
【问题讨论】:
标签: php class object initialization
如果类名存储在字符串中,PHP 是否可以从类名实例化对象?
【问题讨论】:
标签: php class object initialization
是的,当然。
$className = 'MyClass';
$object = new $className;
【讨论】:
如果您的班级需要参数,您应该这样做:
class Foo
{
public function __construct($bar)
{
echo $bar;
}
}
$name = 'Foo';
$args = 'bar';
$ref = new ReflectionClass($name);
$obj = $ref->newInstanceArgs(array($args));
【讨论】:
<?php
$type = 'cc';
$obj = new $type; // outputs "hi!"
class cc {
function __construct() {
echo 'hi!';
}
}
?>
【讨论】:
也是静态的:
$class = 'foo';
return $class::getId();
【讨论】:
您可以通过将类名/方法存储在数据库等存储中来进行一些动态调用。 假设该类对错误具有弹性。
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 服务。
【讨论】: