variable reference problem

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
camiel
Forum Newbie
Posts: 3
Joined: Wed Mar 22, 2006 1:22 am

variable reference problem

Post 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]
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post 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.
Post Reply