Returning an instance of a node itself in a php tree class -
so i'm trying create tree structure in php. don't know if that's possible , i'm not great php difficult me.
the code have far (important stuff only, code has been cut out):
abstract class tree_node { protected $_child_refs = array(); abstract public function add_child($arg); public function count() { return count($this->_child_refs); } public function get_deepest_children() { if ($this->count() === 0) { return $this; } else { foreach ($this->_child_refs $child_ref) { $deepest[] = $child_ref->get_deepest_children(); } } } abstract public function __construct(); } class data_node extends tree_node { private $_data = ""; public function add_child($data) { $new_child = new data_node($data); $this->_child_refs[] = $new_child; } public function __construct($data) { $this->_data = $data; } } $foo = new data_node("foo"); $foo->add_child("bar"); var_dump($foo->get_deepest_children());
this code should return data_node "bar" data instead null. what's wrong "return $this"? not proper way return instance of class itself?
also, feel free critique code/tell me i'm doing wrong. want keep tree functions separate functions specific data stored in tree, why split 2 classes, if think that's bad idea tell me.
this:
public function get_deepest_children() { if ($this->count() === 0) { return $this; } else { foreach ($this->_child_refs $child_ref) { $deepest[] = $child_ref->get_deepest_children(); } } }
should this:
public function get_deepest_children() { if ($this->count() === 0) { return array($this); } $deepest = array(); foreach ($this->_child_refs $child_ref) { $deepest = array_merge($deepest,$child_ref->get_deepest_children()); } return $deepest; }
Comments
Post a Comment