【问题标题】:How to dynamically use class names如何动态使用类名
【发布时间】:2019-01-14 14:57:25
【问题描述】:

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

$myObj =  new Application_Model_XYZtable();

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

我试过了。

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

但不工作。

【问题讨论】:

  • 你不应该使用对象名称,在对象内部添加一个用户选择的属性。

标签: php class object zend-framework


【解决方案1】:

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

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]

【讨论】:

  • 基本上,我在 Zend 框架 1 中工作,Application_Model 定义了路径。因此,如果我使用此方法,则会收到错误 Application_Model_XYZtable not found in the test controller。
  • 我相信您将能够轻松地根据您的情况调整我的通用答案
  • 你是否包含了命名空间?
  • 我包含了受保护的 $_name = "db.Tbalename";在我的课上。你在问这个吗?
  • 不,我的意思是use Application/Model/XYZtable;
猜你喜欢
  • 1970-01-01
  • 2018-12-03
  • 1970-01-01
  • 2018-05-16
  • 1970-01-01
  • 2019-12-11
  • 2021-03-07
  • 1970-01-01
相关资源
最近更新 更多