当转储显示变量设置时,函数返回NULL


Function is returning NULL while dump show variable is set

你好,我有一个愚蠢的问题。我想解析Firewall configuration file。我已经准备了一个脚本,它应该显示文件中第一个条目的所有端口:

    $fileRule = file_get_contents("configurationfile.w");
    $rules = explode(":rule (",$fileRule);
    $rules = array_slice($rules,1,-1);

    foreach($rules as $rule){
        $ports = array();
        if (strpos($rule,'RULE')){
            $serv = getServices($rule);
            $ports = getPorts($serv);
            var_dump($ports);
            exit;break;
        }   
    }

函数getServices($rule)返回一个数组(检查var_dump)和变量$serv设置正确。但是函数getPorts($ports的结果是空的。

    function getPorts($serv){
        $fileObjects = file_get_contents("objects.C");
        $portss = array();
        $ref = array();
        foreach ($serv as $servPoint){
            $portAll = getBetween($fileObjects,": ($servPoint",":type (");
            if (strpos($portAll,': (ReferenceObject')){
                $portExploded = explode(": (ReferenceObject",$portAll);
                $portExploded = array_slice($portExploded,1);
                foreach($portExploded as $refPort){
                    $refName = getBetween($refPort,":Name (",")");
                    array_push($ref, $refName);
                }
                getPorts($ref);
            }
            else{
                $portAll = getBetween($fileObjects,": ($servPoint",":updated_by_sd");
                $port = getBetween($portAll,":port (",")");
                $type = getBetween($portAll,":type (",")");
                array_push($portss,array($port,$type));
            }
        }
        return $portss;
    }

我已经检查了变量$portss(在getPorts中返回)和echoed,它和变量包含适当的值集,但是它在离开函数后没有被传递。

谁能给我一个提示我错过了什么?

编辑var_dump($portss) inside getPorts()的结果

array(4) {
  [0]=>
  array(2) {
    [0]=>
    string(3) "666"
    [1]=>
    string(3) "RDP"
  }
  [1]=>
  array(2) {
    [0]=>
    string(3) "667"
    [1]=>
    string(3) "RDP"
  }
  [2]=>
  array(2) {
    [0]=>
    string(3) "668"
    [1]=>
    string(3) "RDP"
  }
  [3]=>
  array(2) {
    [0]=>
    string(3) "669"
    [1]=>
    string(3) "RDP"
  }
}

在函数getPorts的最后一次执行中(记住这是一个递归函数),您不可能拥有所有数据而不将其返回给主函数。

我认为问题在于,在函数的最后一次执行中,您返回变量$portss,但它是空的,因为您在函数开始时设置了它。

在递归函数中,你需要恢复从函数中的返回的数据,所以你可以做一些事情(我不能给你一个直接的答案,因为我不知道你正在解析的文件)

1。—将this: getPorts($ref);更改为this: $portss = getPorts($ref);,这样可以从该函数的其他执行中恢复数据。

2。-将返回的变量$portss作为参数传递给函数,以便您可以在最后一次执行时访问它