I am wondering, can a class create a new instance of itself from an internal method?

I am trying to create an Oo menu system, with an menuitem object that searches for children, then creates a new instance for each child within itself. I am just wondering if this is the way to go before I start coding?

class menuitem
{
var $text;					# The text menu title
var $uri;					# The Universal Resource Indentifier (URL)
var $levelToken;			# The level this menu is at, passes $levelToken-- to children
var $active;				# Boolean whether this is the active menu
var $children;				# Array to store children of this item
var $title;					# Title tag to apply to link
var $pageName;				# The page name of the link

function menuitem($linkText, $url, $level, $active, $toolTip)
{
	$this->text = $linkText;
	$this->uri = $url;
	$this->levelToken = $level;
	$this->active = $active;
	$this->title = $toolTip;
}

// ... some more methods

function addChild($inputDetails, $type)
{
		$this->children[] = new menuitem($inputDetails['title'], $inputDetails['name'], ($this->levelToken - 1), isActive($inputDetails['name'], $type));
}

As you can see, I am creating a new instance of menuitem as a new child of this instance. Is this possible?

Please would this be legal - I can't find any documentation on whether calling a method of a class within an internal attribute is legal... eg.

$this->children[$i]->printChild();

    It's perfectly possible. Of course, you have to watch out for creating endless loops....

      [FONT=Trebuchet MS]Do you have any documentation for your codes?[/FONT]

        The variable $levelToken value gets handed down to the children decreased by 1 each time. If the $levelToken variable is less than 1, the child does not create any more children. I didn't include the method that controls the levels, but when I finish the class, I'll post the entire thing here for you to look at.

        This is how I control how many levels I want the menu object to include.

        Thank you for your help. I will get on with testing it now and report back my results.

          What you are describing sounds like the Composite pattern. See here for a PHP-based description.

            Write a Reply...