PHP 可以将类名中的对象实例化为字符串吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1377052/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can PHP instantiate an object from the name of the class as a string?
提问by user135295
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 中从类名实例化一个对象?
回答by brianreavis
Yep, definitely.
是的,绝对。
$className = 'MyClass';
$object = new $className;
回答by Mr. Smith
回答by Andrew Atkinson
Static too:
也是静态的:
$class = 'foo';
return $class::getId();
回答by Hugo R
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.
等等。然后在您的代码中使用数据库返回的字符串作为类和方法名称。你甚至可以为你的类存储 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}();
}
}
I use this method to create REST web services.
我使用这种方法来创建 REST Web 服务。
回答by josef
if your class need argumentsyou should do this:
如果您的班级需要参数,您应该这样做:
class Foo
{
public function __construct($bar)
{
echo $bar;
}
}
$name = 'Foo';
$args = 'bar';
$ref = new ReflectionClass($name);
$obj = $ref->newInstanceArgs(array($args));

