我提前為我的英語不好道歉。 我希望你能通過閱讀代碼來理解。
如何獲取運行類的命名空間?
但我不想將NAMEPSACE作為引數傳遞給該方法。
路由.php
namespace sys;
class Route{
static public function getNamespaceOfRunFile(){
echo namespace;
}
}
應用程式/example.php
namespace app\example;
use sys\Route;
Route::getNamespaceOfRunFile(); //echo "app\example"
我必須在 Route 類中獲取“app\example”。
謝謝..
即使我嘗試了下面的答案,我也只能將“sys”輸出輸出到螢屏上。
多虧了你,在確定php沒有我想要的函式后,我只能自己寫下面的函式來達到結果。
非常感謝所有回復的人。
static function getNamespaceOfRunFile(){
$includedFileList = get_included_files();
$lastIncludedFileSrc = end($includedFileList);
$selfFileSrc = __FILE__;
$routeBaseName = pathinfo($selfFileSrc)['basename'];
$lastIncludedFileSrcPart = explode('\\', $lastIncludedFileSrc);
$selfFileSrcPart = explode('\\', $selfFileSrc);
$namespace = '';
foreach($lastIncludedFileSrcPart as $key => $part){
if(
!str_contains($part, $routeBaseName) &&
(!isset($selfFileSrcPart[$key]) || $part !== $selfFileSrcPart[$key]))
{
$namespace .= "$part\\";
}
}
return substr($namespace, 0, -1);
}
我可能需要更流暢地簡化此代碼。雖然我總是可以使用 end() 陳述句訪問正確的檔案,但我不確定在每個專案中是否都會這樣。
uj5u.com熱心網友回復:
無法獲取命名空間 use get_called_class(),甚至debug_backtrace()在example.php檔案中找不到命名空間。
呼叫時使用的get_called_class()回傳值。sys\Routeclass::method()
要找到這樣的呼叫者檔案的命名空間,需要一個小技巧。首先使用回溯獲取呼叫者檔案及其內容,然后使用naholyr 在 GitHub 上創建的函式僅提取命名空間。
這是Route.php 的完整源代碼。
namespace sys;
class Route{
static public function getNamespaceOfRunFile(){
$traces = debug_backtrace();
// get caller file.
foreach ($traces as $trace) {
if (isset($trace['file']) && $trace['file'] !== __FILE__) {
$file = $trace['file'];
break;
}
}
if (!empty($file) && is_file($file)) {
$fileContents = file_get_contents($file);
return (by_token($fileContents));
}
}
}
/**
* @link https://gist.github.com/naholyr/1885879 Original source code.
*/
function by_token ($src) {
$tokens = token_get_all($src);
$count = count($tokens);
$i = 0;
$namespace = '';
$namespace_ok = false;
while ($i < $count) {
$token = $tokens[$i];
if (is_array($token) && $token[0] === T_NAMESPACE) {
// Found namespace declaration
while ( $i < $count) {
if ($tokens[$i] === ';') {
$namespace_ok = true;
$namespace = trim($namespace);
break;
}
$namespace .= is_array($tokens[$i]) ? $tokens[$i][1] : $tokens[$i];
}
break;
}
$i ;
}
if (!$namespace_ok) {
return null;
} else {
return $namespace;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/368479.html
