Page 1 of 1

variable reference problem

Posted: Wed Mar 22, 2006 3:57 am
by camiel
patrikG | Please use

Code: Select all

and

Code: Select all

tags where appropriate when posting code. Read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url][/color]


I am trying to implement a linked list, but havea problem iterating through it when I want to add a node. In order to do this, I need a reference variable (currentNode) to walk through the list, this needs to be a reference because when I use the iteration node to update the list, the original list must show  the changes. The only problem is that when I define a reference variable pointing to the head node of my list, and I change it for iteration, the original reference changes with it. With other words, when I make the new reference point to another variable, the original constant ($this) changes with it   anybody has a clue on how to solve this?

Code: Select all

<?php

class Node{

	var $value;
	var $next;

	function add($number){

		$newNode = new Node;
		$newNode->value = $number;
			
		//insert at head of the list
		if($this->value<$number){
			$newNode->next = $this;
			return $newNode;
		}
		
		$currentNode = & $this;
 		
		while($currentNode->next->value>$number and $currentNode->next != NULL){
			
			$currentNode = $currentNode->next;
		}

		$newNode->next = $currentNode->next;
		$currentNode->next = $newNode;
		
		return $this;					
	}


	function printList(){
		$currentNode = $this;
		while($currentNode != NULL){
			echo $currentNode->value."<BR>";
			$currentNode = $currentNode->next;
		}
	}
}


$head = new Node;
$head->value = 4;
$head = $head->add(10);
$head = $head->add(2);
$head->printList();


?>
patrikG | Please use

Code: Select all

and

Code: Select all

tags where appropriate when posting code. Read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url][/color]

Posted: Wed Mar 22, 2006 9:02 am
by feyd
You're overwriting $head by storing it. You'll need to keep a reference to the original object.

I'm going to guess you're using PHP 4. PHP 4 by default will clone an object unless you tell it to use a reference.