我有一百个班级模型(MVC系统模型) 我如何用关系类创建实例?
类中的例子有这样的方法:
class object {
/**
* Simply create new instance of this object
* @return object
*/
function createNewInstance() {
$class_name = __CLASS__;
$return = new $class_name;
return $return;
}
}
我们可以看到,如果这个类,我使用__CLASS__
获取关系名称
有没有更好的方法来创建实例?
我听说有反射方法吗?
答案 0 :(得分:1)
似乎你需要get_class() http://codepad.org/yu6R1PDA
<?php
class MyParent {
/**
* Simply create new instance of this object
* @return object
*/
function createNewInstance() {
//__CLASS__ here is MyParent!
$class_name = get_class($this);
return new $class_name();
}
}
class MyChild extends MyParent {
function Hello() {
return "Hello";
}
}
$c=new MyChild();
$d=$c->createNewInstance();
echo $d->Hello();
this也有效:
class MyParent {
/**
* Initialise object, set random number to be sure that new object is new
*/
function __construct() {
$this->rand=rand();
}
}
class MyChild extends MyParent {
function Hello() {
return "Hello ".$this->rand;
}
}
$c=new MyChild();
$d=new $c;
echo $c->Hello()."\n";
echo $d->Hello()."\n";