I’m confused about the following output in this linked list
class ListNode{
public $next = NULL;
public $data = NULL;
public function __construct($data){
$this->data = $data;
}
}
class LinkedList{
private $firstNode = NULL;
private $lastNode = NULL;
public function insertFirst($data){
$link = new ListNode($data);
$link->next = $this->firstNode;
$this->firstNode = &$link;
if($this->lastNode == NULL){
$this->lastNode = &$link;
}
}
public function readList(){
while($this->firstNode != NULL){
echo $this->firstNode->data;
$this->firstNode = $this->firstNode->next;
}
}
public function assessList(){
$copy = $this->firstNode;
echo $copy->data;
echo $this->firstNode->data;
$copy->data = 'm';
echo $copy->data;
echo $this->firstNode->data;
}
}
$linkedList = new LinkedList();
$linkedList->insertFirst('c');
$linkedList->insertFirst('b');
$linkedList->insertFirst('a');
//$linkedList->readList(); //output a b c
$linkedList->assessList(); //outputs a a m m
I would expect the output to be a a m a. I thought $copy is just a copy of the value stored in $this->firstNode.
Isn’t this line of code $copy = $this->firstNode an assignment by value? I would expect the output to be a a m m if it was an assignment by reference $copy = &$this->firstNode but not if it was an assignment by value.
Can someone please clarify?
EDIT (additional example)
public function assessList(){
$copy = $this->firstNode->data;
echo $copy. "<br/>";
echo $this->firstNode->data. "<br/>";
$copy = 'm';
echo $copy. "<br/>";
echo $this->firstNode->data. "<br/>";
}
This:
Is not a copy of the object, it’s a copy of the “pointer” to the original object, so when you modify it, you modify the underlying object. You need to use the
clonekeyword to get a true copy:From the PHP docs (emphasis mine):
You can see from this example that your code snippet now outputs: