2016-12-27 13 views
0

我想確定FQCN是類別,特徵還是接口。這是我目前想的,但是有沒有人有更好的想法?確定FQCN是類別,接口還是特性的最佳方法

/** 
* @return string|null Returns the type the FQCN represents, returns null on failure 
*/ 
function fqcnType(string $fqcn) : ?string 
{ 
    if (interface_exists($fqcn) === true) { 
     return 'interface'; 
    } elseif (class_exists($fqcn) === true) { 
     return 'class'; 
    } elseif (trait_exists($fqcn) === true) { 
     return 'trait'; 
    } elseif (function_exists($fqcn) === true) { 
     return 'function'; 
    } 

    return null; 
} 

function fqcn_exists(string $fqcn) : bool 
{ 
    return fqcnType($fqcn) !== null; 
} 

回答

1
/** 
* @return string|null Returns the type the FQCN represents, returns null on failure 
*/ 
function fqcnType(string $fqcn) : ?string 
{ 
    $types = [ 
     'interface', 
     'class', 
     'trait', 
     'function', 
    ]; 

    foreach($types as $type) { 
     if(true === ($type.'_exists')($fqcn)) { 
      return $type; 
     } 
    } 

    return null; 
} 

function fqcn_exists(string $fqcn) : bool 
{ 
    return null !== fqcnType($fqcn); 
} 
+0

感謝您對這個代碼片段,它可以提供即時幫助。通過展示*爲什麼*這是一個很好的解決方案,對未來的讀者會有更好的解決方案,這將爲它的教育價值提供一個合適的解釋[//大大提高](// meta.stackexchange.com/q/114762)但不完全相同的問題。請編輯您的答案以添加解釋,並指出適用的限制和假設。 –

相關問題