递归for循环

时间:2015-05-15 16:05:14

标签: php recursion

我有一个对象树(全部是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
    //...

1 个答案:

答案 0 :(得分:1)

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