如何在php中创建类的对象,方法是中间部分可以根据请求进行更改?
$myObj = new Application_Model_XYZtable();
XYZ是可更改的部分,取决于用户的要求。
我尝试过这个。
$myObj = new Application_Model_ . $XYZ . table();
但不起作用。
答案 0 :(得分:0)
使用字符串定义类的整个名称。
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]