php - 如何动态使用类名
问题描述
如何在 php 中创建类的对象,中间部分可以根据请求更改?
$myObj = new Application_Model_XYZtable();
XYZ 是可变部分,取决于用户的要求。
我试过这个。
$myObj = new Application_Model_ . $XYZ . table();
但不工作。
解决方案
使用字符串来定义类的全名。
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]
推荐阅读
- android - 启动另一个意图的活动不起作用
- google-chrome - Chrome 中 CTAP2 (FIDO2) 协议的不完整实现?
- php - PHP - 如何打印具有特定模式的字符串?(词搜索网格)
- java - Ajax 调用数据不绑定
- git - 使用 Netbeans 连接到 azure devops GIT 存储库时出现“不正确的凭据”错误
- python - 如何动态定义窗口名称变量
- javascript - 使用 emit 切换变量值
- python - Python:是否可以在列表声明中使用列表推导?
- delphi - 当我执行 OnDblClick 事件 (Form1) 以打开 Form2 时,它会触发 Form2 的 OnCellClick 事件,而无需单击 form2 网格
- github - 如何在 GitHub markdown 中转义反斜杠