如何在 PHP 中獲取已定義的名稱空間列表


給定檔案 1 具有名稱空間 ns_1,檔案 2 具有名稱空間 ns_2,如果檔案 1 和檔案 2 包含在檔案 3 中,則無法得知已載入名稱空間 ns_1 和 ns_2。

唯一的方法是使用“class_exists”函式,可以使用“get_declared_classes”獲取具有特定名稱空間的類列表。簡單來說,可以利用獲取的這些資料,透過給定所有宣告的類名,找到匹配的名稱空間 −

function namespaceExists($namespace) {
   $namespace .= "\";
   foreach(get_declared_classes() as $name)
   if(strpos($name, $namespace) === 0) return true;
   return false;
}

----或---

範例

 線上演示

<?php
namespace FirstNamespace;
class new_class {}
namespace SecondNamespace;
class new_class {}
namespace ThirdNamespace\FirstSubNamespace;
class new_class {}
namespace ThirdNamespace\SecondSubNamespace;
class new_class {}
namespace SecondNamespace\FirstSubNamespace;
class new_class {}
$namespaces=array();
foreach(get_declared_classes() as $name) {
   if(preg_match_all("@[^\\]+(?=\\)@iU", $name, $matches)) {
      $matches = $matches[0];
      $parent =&$namespaces;
      while(count($matches)) {
         $match = array_shift($matches);
         if(!isset($parent[$match]) && count($matches))
         $parent[$match] = array();
         $parent =&$parent[$match];
      }
   }
}
print_r($namespaces);

輸出結果

將會產生以下輸出

Array ( [FirstNamespace] => [SecondNamespace] => Array ( [FirstSubNamespace] => ) [ThirdNamespace] => Array ( [FirstSubNamespace] => [SecondSubNamespace] => ) )

建立了不同的名稱空間(FirstNamespace、SecondNamespace..)並聲明瞭空類(new_class)。建立了一個名稱空間陣列,使用 foreach 迴圈遍歷宣告的類。執行正則表示式匹配,並會顯示在該特定環境中定義的名稱空間。

更新於:09-Apr-2020

516 次瀏覽

開啟您的 事業

完成課程即可獲得證書

開始
廣告
© . All rights reserved.