douxiong4892
2013-08-06 18:57 阅读 14
已采纳

使用tokenizer获取代码的返回值

I'm trying to parse PHP source code with the token_get_all(). So far everything worked out with that function, but now i need a way to get the return values of methods.

Identifying where a return is done isn't the problem. I just see no way of getting the piece of code that comes after the return value.

For example for this piece of code:

<?php
    class Bla {
        public function Test1()
        {
            $t = true;

            if($t) {
                return 1;
            }

            return 0;
        }

        public function Test2()
        {
            echo "bbb";
            return; // nothing is returned
        }

        public function Test3()
        {
            echo "ccc";
            $someval1 = 1;
            $someval2 = 2;

            return ($someval + $otherval)*2;
        }
    }
?>

I'm using get_token_all() to identify where a return is done:

$newStr  = '';
$returnToken = T_RETURN;
$tokens = token_get_all($source);
foreach ($tokens as $key => $token)
{    
    if (is_array($token))
    {
        if (($token[0] == $returnToken))
        {
            // found return, now get what is returned?
        }
        else
        {
            $token = $token[1];
        }
    }

    $newStr .= $token;
}

I have no clue how to get the piece of code that is actually returned. That is what i want to get.

Anyone any idea how i could do this?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    duanjue6584 duanjue6584 2013-08-06 20:08

    Perhaps this might help. Though I curious to know what you are ultimately trying to do.

    $tokens = token_get_all($str);
    $returnCode = '';
    $returnCodes = array();
    foreach ($tokens as $token) {
        // If return statement start collecting code.
        if (is_array($tokens) && $token['0'] == T_RETURN) {
            $returnCode .= $token[1];
            continue;
        }
    
        // if we started collecting code keep collecting.
        if (!empty($returnCode)) {
            // if we get to a semi-colon stop collecting code
            if ($token === ';') {
                $returnCodes[] = substr($returnCode, 6);
                $returnCode = '';
            } else {            
                $returnCode .= isset($token[1]) ? $token[1] : $token;
            }
        }
    }
    
    点赞 评论 复制链接分享

相关推荐