剛好有人問,就貼出來了
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!