2011-01-06 58 views
0

我在PHP中的下列對象創建行:使用字符串創建一個對象

$countryTargetSearchParameter = new CountryTargetSearchParameter(array(new CountryTarget('JP'))); 

我想用來替換:

$countryTargetSearchParameter = new CountryTargetSearchParameter(array($LocArray)); 

其中$ LocArray等於新CountryTarget ('J.P')。但是,我無法得到這個工作。我能否得到一些幫助?

謝謝

+0

你在試圖達到什麼目的?你爲什麼不在你的構造函數中創建數組,而不是試圖在創建時傳入數組? – 2011-01-06 22:03:27

回答

0
class CountryTargetSearchParameter { 
    public function __construct(array $array_with_string) { 
     $this->new_object = new CountryTarget($array_with_string[0]); 
    } 
} 
$array_with_string = array('JP'); 
$test = new CountryTargetSearchParameter($array_with_string); 

或者,更清潔,並使用字符串類:

class CountryTargetSearchParameter { 
    public function __construct($name_of_class, $parameter) { 
     $this->new_object = new $name_of_class($parameter); 
    } 
} 
$test = new CountryTargetSearchParameter('CountryTarget', 'JP'); 
+0

。謝謝斯蒂芬。我正在尋找的答案非常簡單。我只是不得不使用eval函數 – Jai 2011-01-18 19:54:21