【问题标题】:php function returning null valuephp函数返回空值
【发布时间】:2013-04-11 22:17:07
【问题描述】:

我正在递归地搜索一个树节点的父节点,然后尝试在一个数组中返回它的父类别。

该函数接收并传递给自己一个最终返回的每个父级的数组。

虽然这个数组有元素,但是在函数外查看return之前的语句是nul

为了让它工作,我只是通过引用制作了参数。但是为什么总是nul呢?

这是我的代码:

function getParent($id,$parents){ // to work changed this to getParent($id,&$parents)

    if($id < 2) { // 1 is the Top of the Tree , so job is done
        return $string;    
    }

     $child = DB::fetchExecute((object)array( // pdo query for category to get parents
     'sql'   => "category",
     'values'=>  array($id),
     'single'=>  1,
     'debug' =>  0)
     );

    $parent = DB::fetchExecute((object)array( // pdo query for parents info
        'sql'   => "category",
        'values'=>  array($child->native_parent_category_id),
        'single'=>  1,
        'debug' =>  0)
    );
    $string[]= "<li>$parent->name ($parent->native_category_id)</li>
        ";        

    getParent($parent->native_category_id , $parents);    
}

// call function
$array = array();
$returnString = getParent($id,$string);

var_dump($returnString,$array); // will both be NULL, or if called by Reference $array has the goods

?>

【问题讨论】:

  • $string 如果$id &lt; 2 则在没有设置的情况下被返回。您只是设置它,但从未将其传递给递归调用

标签: php recursion


【解决方案1】:

变化:

function getParent($id,$parents){

收件人:

function getParent($id,$parents, $string){

然后改变:

getParent($parent->native_category_id , $parents);

收件人:

getParent($parent->native_category_id , $parents, $string);

$string 的作用域仅在函数运行时存在 - 因此,如果您重新运行该函数,它将重置其中的所有变量。每次重新运行时都需要发送变量。

【讨论】:

    【解决方案2】:

    我会在函数之前声明$string,在函数内部,在顶部使用global $string;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-17
      • 1970-01-01
      • 2013-08-05
      相关资源
      最近更新 更多