I have two classes, LinkedList
and Node
.
In both I have a function printToArray()
. I would like to call this as demonstrated, and have it return an array.
In the Node
class in printToArray(), you can see how I'm attempting to return the array. If I call, var_dump($aNodeList)
, I can see the array is formed correctly, but its just not returning!
Would someone please mind explaining why this isn't working, or what I can go and read to find out.
From the following I would be expecting to see an array like such returned;
array(4) {
[0]=>
string(4) "adam"
[1]=>
string(4) "andy"
}
n.b. I'm not sure what to call this post. If anyone can suggest an improvement please do.
Many Thanks
Classes (excluding getters setters )
class LinkedList{
private $head;
function __construct() {
$this->head = null;
}
public function addNode($data){
if( $this->head == null ){
$this->head = new Node( $data );
} else {
$this->head->addNode( new Node( $data ) );
}
}
public function printToArray(){
$aNodeList = array();
try{
// I expect the array to be returned here
var_dump($this->head->printToArray($aNodeList) );
} catch (exception $e){
echo 'Caught exception: ', $e->getMessage(), "
";
}
}
}
class Node{
private $data = null;
private $link;
// Node constructor
function __construct($data) {
$this->data = $data;
$this->link = null;
}
public function nextNode(){
if($this->link == null){
throw new Exception("<span style=\"color:red\">Error..etc</span>
");
}
return $this->link;
}
public function addNode($newNode){
if($this->link == null){
$this->link = $newNode;
}else{
$this->nextNode()->addNode($newNode);
}
}
public function printToArray($aNodeList){
$aNodeList[] = $this->data;
if($this->link == null){
return $aNodeList;
exit;
}
$this->nextNode()->printToArray($aNodeList);
}
}
To init
$oLinkList = new LinkedList;
$oLinkList->addNode('adam', null);
$oLinkList->addNode('andy', null);
var_dump($oLinkList);