刚好有人问,就贴出来了
PHP支持以【字符串】作为【对象类型名称】的创建方式
直接看例子:
class apple{
function get(){
return "I'm APPLE";
}
}
class apple2{
function get(){
return "I'm APPLE #2";
}
}
$str="apple2";
$object=new $str;
echo $object->get();
//会输出 I'm APPLE #2
更进一步的,传参也没问题
class apple{
protected $tmp;
public function __construct($str) {
$this->tmp=$str;
}
function get(){
return "APPLE:$this->tmp";
}
}
class apple2{
function get(){
return "I'm APPLE #2";
}
}
$str="apple";
$object=new $str("is Good!");
echo $object->get(); //会输出 APPLE:is Good!