递归for循环中的访问变量


Access variable in recursive for loop

我有一个对象树(所有是在PHP)。

我想递归地遍历它。在递归函数中是一个循环。我想访问之前调用给出的变量,但是我不能。我可以在循环之外访问变量:

protected function saveTree($tree, $fk=null)
{
    echo $fk; //this works
    $objects = $tree->getChildren();
    for($i=0; $i<count($objects); $i++) 
    {
        echo $fk; //don't work
        //...
        $this->saveTree($objects[$i], $id);  
    }
}

如何访问$fk变量?

编辑:

这是我的"树类"

abstract class Element
{
    protected $name;
    protected $parentNode;
    protected $object; 
    protected $dbId;
    public function getParent()
    {
        return $this->parentNode;
    }
    public function setParentNode($parentNode)
    {
        $this->parentNode = $parentNode;
    } 
    public function getObject()
    {
        return $this->object;
    }
    public function setObject($object)
    {
        $this->object = $object;
    }
    public function getName()
    {
        return $this->name;
    }
    public function setName($name)
    {
        $this->name = $name;
    }
    public function getDbId() 
    {
        return $this->dbId;
    }
    public function setDbId($dbId)
    {
        $this->dbId = $dbId;
    }
    public function  setData($data) {
        $this->object->exchangeArray($data);
    }
}
class Node extends Element 
{    
    protected $children = array();
    function __construct($parentNode)
    {
        $this->parentNode = $parentNode;
    }
    public function pushChild($child)
    {
        if($child) {
            array_push($this->children, $child);
        }
    }
    public function getChildren() 
    {
        return $this->children;
    }
}
下面是完整的递归方法:
protected function saveTree($tree, $fk=null)
{
    $objects = $tree->getChildren();
    echo count($objects); //This works
    echo $fk; //This works also
    for($i=0; $i<count($objects); $i++) 
    {
        echo 'test'; //this works
        echo $fk; //this doesn't work

        $parent = $objects[$i]->getParent();
        $config = $this->getConfig();
        $table = array_search($objects[$i]->getName(), $config); 
        $objects[$i]->getObject()->setChildren($objects[$i]->getChildren());
        $objects[$i]->setObject($table->save($objects[$i]->getObject()));
        if($objects[$i]->getObject()) {
            //the condition is tested and in every test-case true
            $id = $objects[$i]->getObject()->getId();
            $objects[$i]->setDbId($id);
            echo $id; //this works
        }
        $this->saveTree($objects[$i], $id);  
    }    
}

与foreach是相同的问题吗?

//...
echo $fk; //work
foreach($tree->getChildren() as $object) 
{
    echo $fk; //don't work
    //...

count($objects)返回0,因此PHP永远不会进入循环,这就是为什么$fk永远不会被多次回显的原因。