首页 > 解决方案 > 如何动态使用类名

问题描述

如何在 php 中创建类的对象,中间部分可以根据请求更改?

$myObj =  new Application_Model_XYZtable();

XYZ 是可变部分,取决于用户的要求。

我试过这个。

$myObj =  new Application_Model_ . $XYZ . table(); 

但不工作。

标签: phpclassobjectzend-framework

解决方案


使用字符串来定义类的全名。

class_exists()可以用来判断一个类是否存在。

例如:

class testABCtest
{

}

class testDEFtest
{

}

$abc = 'abc';
$def = 'def';

$myclass1 = 'test' . $abc . 'test';
$myclass2 = 'test' . $def . 'test';
$myclass3 = 'IDontExists';

$obj1 = new $myclass1();
//          ^-------^--------+
$obj2 = new $myclass2(); //  +----Notice the whole names being variables (string)
//          ^-------^--------+
if (class_exists($myclass3))
{
    $obj3 = new $myclass3();
    var_dump($obj3);
}
else
    var_dump($myclass3 . " does not exist.");
var_dump($obj1, $obj2);

输出

C:\wamp64\www\New folder\test11.php:30:string 'IDontExists does not exist.' (length=26)
C:\wamp64\www\New folder\test11.php:33:
object(testABCtest)[1]
C:\wamp64\www\New folder\test11.php:33:
object(testDEFtest)[2]

推荐阅读