2016-12-27 4 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)、将来の同様の、しかし、同一ではない質問。説明を追加するためにあなたの答えを[編集]し、どんな制限と前提が適用されるかを示してください。 –

関連する問題