douxiong4892 2013-08-06 18:57
浏览 15
已采纳

使用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 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;
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程