I am creating a linklist class and have some confusion about reference to objects.
As per my understanding by default object is copied by reference. $Obj1 = $Obj2. $Obj1 is a alias of $Obj2.
Can someone please point out which one is correct in linkedlist implementation.
$firstNode->next = $this->first;---> seems to be correct
or
$firstNode->next =& $this->first;
$this->first = $firstNode;-----> seems to be correct as $firstNode is an object
or
$this->first = & $firstNode;
code:
class Node {
public $element;
public $next;
public function __construct($element){
$this->element = $element;
$this->next = NULL;
}
}
class Linklist {
private $first;
private $listSize;
public function __construct(){
$this->first = NULL;
$this->listSize = 0;
}
public function InsertToFirst($element){
$firstNode = new Node($element);
$firstNode->next = $this->first; // or $firstNode->next =& $this->first;
$this->first = $firstNode; // or $this->first = & $firstNode;
}
In PHP you do not need to use reference assignment (aliasing/
&) for your linked list if each node is an object itself andnextandfirstare objects of that node-type as well.See Objects and References in the PHP Manual to understand the details.