Page 1 of 1

php classes problem

Posted: Wed Mar 22, 2006 1:30 am
by camiel
feyd | Please use

Code: Select all

and

Code: Select all

tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]


I am trying to implement an unordered linked list in PHP (with which I am not very experienced),
but somehow, instances of the Node class I created do not store the attributes as soon as a new node is inserted. This link to the next node does seem to stay in tact however.Below is a simplified version of the code, can anybody tell me what O am doing wrong? The program now only prints uit value 4, and empty strings for the other node values..

Code: Select all

<?php

class Node{

	var $value;
	var $next;

	//insert at head of the list
	function add($number){
		$newNode = new Node;
		$newNode->$value = $number;
		$newNode->next = $this;			
		return $newNode;
	}
}


$head = new Node;
$head->value = 4;

$head = $head->add(10);
$head = $head->add(6);

echo "value of first node = ".$head->value."<BR>";
echo "value of second node = ".$head->next->value."<BR>";
echo "value of third node = ".$head->next->next->value."<BR>";


?>

feyd | Please use

Code: Select all

and

Code: Select all

tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]

Posted: Wed Mar 22, 2006 1:46 am
by feyd
try changing

Code: Select all

$newNode->$value = $number;
to

Code: Select all

$newNode->value = $number;

Posted: Wed Mar 22, 2006 2:29 am
by camiel
Ahh that dit the trick, thanks.
alot :D