从PHP中的文件内容获取完全限定的类名

<?php

function get_class_from_file($path_to_file)
{
    //Grab the contents of the file
    $contents = file_get_contents($path_to_file);

    //Start with a blank namespace and class
    $namespace = $class = "";

    //Set helper values to know that we have found the namespace/class token and need to collect the string values after them
    $getting_namespace = $getting_class = false;

    //Go through each token and evaluate it as necessary
    foreach (token_get_all($contents) as $token) {

        //If this token is the namespace declaring, then flag that the next tokens will be the namespace name
        if (is_array($token) && $token[0] == T_NAMESPACE) {
            $getting_namespace = true;
        }

        //If this token is the class declaring, then flag that the next tokens will be the class name
        if (is_array($token) && $token[0] == T_CLASS) {
            $getting_class = true;
        }

        //While we're grabbing the namespace name...
        if ($getting_namespace === true) {

            //If the token is a string or the namespace separator...
            if(is_array($token) && in_array($token[0], [T_STRING, T_NS_SEPARATOR])) {

                //Append the token's value to the name of the namespace
                $namespace .= $token[1];

            }
            else if ($token === ';') {

                //If the token is the semicolon, then we're done with the namespace declaration
                $getting_namespace = false;

            }
        }

        //While we're grabbing the class name...
        if ($getting_class === true) {

            //If the token is a string, it's the name of the class
            if(is_array($token) && $token[0] == T_STRING) {

                //Store the token's value as the class name
                $class = $token[1];

                //Got what we need, stope here
                break;
            }
        }
    }

    //Build the fully-qualified class name and return it
    return $namespace ? $namespace . '\\' . $class : $class;

}

摘自:http://jarretbyrne.com/2015/06/197/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值