【问题标题】:How can I get the namespace where the Class is run?如何获取运行类的命名空间?
【发布时间】:2022-01-05 08:49:03
【问题描述】:

我为我的英语不好提前道歉。 我希望你能通过阅读代码来理解。

如何获取运行类的命名空间?
但我不想将 NAMEPSACE 作为参数传递给方法。

Route.php

namespace sys;

class Route{
    static public function getNamespaceOfRunFile(){
        echo namespace;
    }
}

app/example.php

namespace app\example;
use sys\Route;

Route::getNamespaceOfRunFile(); //echo "app\example"

我必须在 Route 类中获取“app\example”。

谢谢..

【问题讨论】:

  • 这个code snippet 可能足够简短和甜蜜。
  • 你不能超越sys 可能是因为我的代码使用$trace[0]['file'][0] 不是你之前调用的文件(或调用者)。我没有测试您的新代码,但请注意在文件路径上爆炸 \\ 可能仅适用于 Windows 路径。我建议首先将它们从任何路径分隔符规范化为\\
  • 我已经更新了代码来获取调用者文件,以防你仍然感兴趣。

标签: php namespaces


【解决方案1】:

无法获取命名空间使用get_called_class(),即使debug_backtrace()example.php 文件中也找不到命名空间。

get_called_class() 返回 sys\Route,与调用的 class::method() 相同。

要像这样找到调用者文件的命名空间需要一个小技巧。首先使用回溯获取调用者文件及其内容,然后使用naholyr on 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;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-31
    • 2013-05-15
    • 1970-01-01
    • 2014-05-10
    相关资源
    最近更新 更多