[英]Why can you instantiate a class from a string variable but not a string in PHP?
[英]Can PHP instantiate an object from the name of the class as a string?
如果类名存储在字符串中,是否可以在 PHP 中从类名实例化一个对象?
是的,绝对。
$className = 'MyClass';
$object = new $className;
<?php
$type = 'cc';
$obj = new $type; // outputs "hi!"
class cc {
function __construct() {
echo 'hi!';
}
}
?>
如果您的班级需要参数,您应该这样做:
class Foo
{
public function __construct($bar)
{
echo $bar;
}
}
$name = 'Foo';
$args = 'bar';
$ref = new ReflectionClass($name);
$obj = $ref->newInstanceArgs(array($args));
也是静态的:
$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 服务。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.