Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP单链表,外部方法生成的返回数组_Php_Oop_Linked List - Fatal编程技术网

PHP单链表,外部方法生成的返回数组

PHP单链表,外部方法生成的返回数组,php,oop,linked-list,Php,Oop,Linked List,我有两个类,LinkedList和Node 在这两者中,我都有一个函数printToArray()。我想像演示的那样调用它,并让它返回一个数组 在printToArray()中的节点类中,您可以看到我如何尝试返回数组。如果我调用,var\u dump($aNodeList),我可以看到数组的格式是正确的,但它没有返回 请有人解释一下为什么这不起作用,或者我可以去读些什么来找出答案 从下面的内容中,我希望看到这样的数组返回 array(4) { [0]=> string(4) "ad

我有两个类,
LinkedList
Node

在这两者中,我都有一个函数
printToArray()
。我想像演示的那样调用它,并让它返回一个数组

在printToArray()中的
节点
类中,您可以看到我如何尝试返回数组。如果我调用,
var\u dump($aNodeList)
,我可以看到数组的格式是正确的,但它没有返回

请有人解释一下为什么这不起作用,或者我可以去读些什么来找出答案

从下面的内容中,我希望看到这样的数组返回

array(4) {
  [0]=>
  string(4) "adam"
  [1]=>
  string(4) "andy"
}
n、 我不知道该怎么称呼这个帖子。如果有人能提出改进建议,请提出

非常感谢

类(不包括getter setter)

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(), "\n";
        }
    }
}


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>\n\n");
        }
        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);

    }

}

你应该写下你有什么错误“不工作”并没有说太多Hanks Robert更新了我的问题。看了这么久,结果对我来说似乎很明显,很抱歉你意识到PHP实际上没有必要编写你自己的单链接列表Cheers Mark,我试图创建它是为了提高我对oop的理解。正在努力理解为什么我不能在LinkedList类中将数组返回给调用方法
$oLinkList = new LinkedList;
$oLinkList->addNode('adam', null);
$oLinkList->addNode('andy', null);

var_dump($oLinkList);