Page 1 of 1

Linked List (and then some) - Refs and not Clones

Posted: Tue May 23, 2006 12:00 pm
by TheMoose
Below is going to be some code, some of which I cut out (has absolutely nothing to do with my test case).

My first question is, am I even doing this properly? I've done OOP before (in C/C++), so my initial feeling is yes, it's fine, but I like to make sure. And since there are no pointers in PHP, I want to make sure I'm referencing references (get it? :)) properly.

Secondly, I want to make sure that in the tester.php file that I'm not referencing simply a clone of an object, that it's the original object I created (efficiency/memory reduction).

I start by making the object, then the AddChild returns a new (child) object, that I reference. Now everytime I call $s and $t, I should be directly accessing the original child that was created, correct? I'm not sure, because the member function takes and returns an object by value, but in the tester, it's using a reference to that object. Now is that referencing a clone, or the object I passed to AddChild? If it's a clone, should I pass the childObject by reference, and just return that childObject instead of the one inside the childForums array?

I searched on keywords like "linked lists", "references", "clones", etc, and nothing really came up to help me all that much :(

It's not extremely important, this is just a fun side project for me. I just like to have efficient and clean (and sometimes even pretty) code.

Thanks in advance,
- Joe (Moose)

tester.php

Code: Select all

require_once("class_forum.php");

$myTop = new Forum(1, "Top Forum", 1);
$t =& $myTop->AddChild(new Forum(2, "Sub 1", 1));
$s =& $myTop->AddChild(new Forum(3, "Sub 2", 2));

$t->AddChild(new Forum(6, "Sub 1-1", 1));
$t->AddChild(new Forum(7, "Sub 1-2", 2));
$s->AddChild(new Forum(8, "Sub 1-1", 1));
$s->AddChild(new Forum(9, "Sub 1-2", 2));

print($myTop->myForumName);
print("<br>");
$myObj =& $myTop->GetChildByName("Sub 2");
$myObj2 =& $myObj->myParentForum;
print($myObj2->myForumName);

class_forum.php

Code: Select all

class Forum {
	var $myForumID;
	var $myForumName;
	var $myParentForum;
	var $myChildForums;
	var $mySequenceNumber;

	function Forum($fid, $fname, $fseq) {
		$this->myForumID = $fid;
		$this->myForumName = $fname;
		$this->mySequenceNumber = $fseq;
		$this->myChildForums = array();
	}

	function AddChild($childForum) {
		$childForum->myParentForum =& $this;
		$this->myChildForums[] = $childForum;
		return $this->myChildForums[count($this->myChildForums)-1];
	}

	function GetChildByName($childName) {
		for($i=0; $i<count($this->myChildForums); $i++) {
			if($this->myChildForums[$i]->myForumName == $childName) {
				$tokill = $i;
				break;
			}
		}
		return $this->myChildForums[$tokill];
	}
}