2014-01-15 19 views
0

創建具有所需類型的類對象是否有創建類對象類型基於var值?PHP - 根據var

示例我想怎樣做:

說我有一些幾十類:ClassA的,ClassB的和ClassC,...這是所有擴展ClassBasic類的。所以它們具有相同的接口函數doOperation(),但內部實現不同。

// the variable contains the name of the desired class type. 
$TypeToCreate = "ClassC"; 

// create the desired type of class 
$ClassObj = new $TypeToCreate; 

// do some operation of the created class. 
$ClassObj->doOperation(); 
+4

這是[工廠模式](http://www.phptherightway.com/pages/Design-Patterns.html)解決的問題 –

+0

$ ClassObj = new $ TypeToCreate應該可以工作,這是什麼問題? – mpm

+0

使用工廠模式,或參見[this](http://stackoverflow.com/questions/534159/instantiate-a-class-from-a-variable-in-php) –

回答

0

抱歉,MPM是正確的, 它的工作原理。還好吧。

我也將看看因素模式,以瞭解它是什麼。

謝謝!