Function recursivity versus variable scope
Posted: Tue Aug 19, 2008 7:49 am
Hy guys,
I need some advice on <post subject>
I am using recursivity to browse through some classes tree containing references. Mainly think of an object of class tree holding an array of references to another objects:
<?php
class tree {
var $name;
function __construct($leafname){
$this->name = $leafname;
}
function add_leaf ($leafname) {
$this->leafs[count($this->leafs)] = new tree($leafname);
}
}
What I want now is to search recursively through this tree for a particular name let's say and return the object:
function search_tree($obj, $search_string, $rec = false) {
global $ret;
if (!$rec) unset ($ret);
if ($obj->name == $search_string)
$ret = $obj;
if (isset($this->leafs))
foreach ($this->leafs as $leaf)
search_tree ($obj, $search_string, true);
if (!$rec) return $ret;
}
$root = populate_tree_from_db();
search_tree ($root, 'What string you want');
?>
Pretty straightforward I think, ok? The only problem is that the global variable $ret doesn't make it to the first recursion and the function doesn't return anything. I am sure I am missing something but don't know exactly what.
Can anybody help me?
Thank you in advance
I need some advice on <post subject>
I am using recursivity to browse through some classes tree containing references. Mainly think of an object of class tree holding an array of references to another objects:
<?php
class tree {
var $name;
function __construct($leafname){
$this->name = $leafname;
}
function add_leaf ($leafname) {
$this->leafs[count($this->leafs)] = new tree($leafname);
}
}
What I want now is to search recursively through this tree for a particular name let's say and return the object:
function search_tree($obj, $search_string, $rec = false) {
global $ret;
if (!$rec) unset ($ret);
if ($obj->name == $search_string)
$ret = $obj;
if (isset($this->leafs))
foreach ($this->leafs as $leaf)
search_tree ($obj, $search_string, true);
if (!$rec) return $ret;
}
$root = populate_tree_from_db();
search_tree ($root, 'What string you want');
?>
Pretty straightforward I think, ok? The only problem is that the global variable $ret doesn't make it to the first recursion and the function doesn't return anything. I am sure I am missing something but don't know exactly what.
Can anybody help me?
Thank you in advance