代码之家  ›  专栏  ›  技术社区  ›  GOsha

如何返回静态变量PHP

  •  -2
  • GOsha  · 技术社区  · 15 年前
    function build_path($cid)
    {
        static $fr=array();
        $DB = new MySQLTable;
        $DB->TblName = 'shop_categories';
        $where['cat_id']['='] = $cid;
        $res = $DB->Select('cat_id,cat_name,cat_parent', $where);
        if($res !== false)
        {
            $pid = mysql_fetch_array($res);
            if($pid['cat_parent'] !== "0")
            {
               $fr[] = $pid['cat_id'];
               build_path($pid['cat_parent']);
            } else {
                $fr[] = $cid;
                $fr = array_reverse($fr);
                print_r($fr);
                return $fr;
            }
        }
    }
    
    print_r(build_path(100));
    

    为什么在函数中使用print\r,但second print\r返回NULL?

    4 回复  |  直到 15 年前
        1
  •  4
  •   Mike B    15 年前

    通常,要使递归函数工作,需要在调用自身时返回一些内容。

    在第一个嵌套if块中尝试以下操作:

    return build_path($pid['cat_parent']);
    
        3
  •  0
  •   zerkms    15 年前

    递归函数不能使用 static

    你为什么需要这条线:

    if($res !== false)
    

        4
  •  0
  •   powtac    15 年前

    而不是 build_path($pid['cat_parent']); 第14行使用 return build_path($pid['cat_parent']);