2016-11-23 26 views
1

我有一個factory,我想返回一個::class從。但是,工廠可能會返回幾十種不同的類型(由傳入工廠的對象類型決定),名爲TypeOneObject,TypeTwoObject等。是否可以使用變量返回類,如下所示?從php工廠返回變量類名稱

$type = $myrequiredclass->getType(); 
return $type."Object"::class; // wanting TypeOneObject::class 

好像不管我怎麼構建這個return語句我總是PHP Parse error: syntax error, unexpected '::'

我知道這將會是很容易有一個大if/thenswitch做的,但我想,以避免。

這裏有一個更充實的場景:

class TypeOneObject 
{ 
    public static function whoAreYou() 
    { 
     return 'Type One Object!'; 
    } 
} 

class MyRequiredClass 
{ 
    public function getType() 
    { 
     return 'TypeOne'; 
    } 
} 

class MyFactory 
{ 
    public static function getFactoryObject(MyRequiredClass $class) 
    { 
     $type = $class->getType()."Object"; 
     return $type::class; 
    } 
} 

$object = MyFactory::getFactoryObject(new MyRequiredClass()); 
$object::whoAreYou(); 
+0

'{$類型。 「對象」} :: class'或也許'()'?一個[mcve]將有助於輕鬆測試。 – Xorifelse

+0

'$ myrequiredclass'是什麼? –

+0

'$ type :: class;'你到底在想什麼':: class'位在那裏?只要刪除它,然後在最後一行添加一個「echo」,你就完成了設置。這就是說,我沒有看到這個例子中工廠的目的。 –

回答

0

$type實例獲取類名的最好方法是使用PHP get_class_methods功能。這將使我們獲得類實例中的所有方法。從那裏我們可以過濾並使用call_user_func來調用該方法並獲取正確的值。

class TypeOneObject 
{ 
    public static function whoAreYou() 
    { 
     return 'Type One Object!'; 
    } 
} 

class MyRequiredClass 
{ 
    public function getType() 
    { 
     return 'TypeOne'; 
    } 
} 

class MyFactory 
{ 
    public static function getFactoryObject(MyRequiredClass $class) 
    { 
     $methods = get_class_methods($class); 
     $method = array_filter($methods, function($method) { 
      return $method == 'getType'; 
     }); 

     $class = new $class(); 
     $method = $method[0]; 
     $methodName = call_user_func([$class, $method]); 
     $objectName = sprintf('%sObject', $methodName); 

     return new $objectName; 
    } 
} 

$object = MyFactory::getFactoryObject(new MyRequiredClass()); 
echo $object::whoAreYou(); 

輸出

Type One Object!