-2
我试图建立一个linkList。一切工作正常,除了我的功能createLinkList
。有一个if条件来指定它是否是第一个条目。我认为这个问题与我在else
中的逻辑有关。任何人都可以阻止正在发生的事情?PHP链接列表,输出第一个和最后一个
我希望从我的例子输出是像
object(createLinkList)#1 (1) {
["head"]=>
object(node)#2 (2) {
["data":"node":private]=>
string(4) "adam"
["link":"node":private]=>
object(node)#3 (2) {
["data":"node":private]=>
string(4) "andy"
["link":"node":private]=>
object(node)#4 (2) {
["data":"node":private]=>
string(4) "ben"
["link":"node":private]=>
}
//and so on...
}
}
}
,而不是我得到;
object(createLinkList)#1 (1) {
["head"]=>
object(node)#2 (2) {
["data":"node":private]=>
string(4) "adam"
["link":"node":private]=>
object(node)#3 (2) {
["data":"node":private]=>
string(4) "eric"
["link":"node":private]=>
*RECURSION*
}
}
}
这是我的代码,它应该运行良好。真的很感谢有人解释我做错了什么。由于
$oLinkList = new createLinkList;
$oLinkList->createLinkList($aList);
echo "<pre>";
var_dump($oLinkList);
class createLinkList{
// // link to the first node
public $head;
// link to the last node
// public $tail;
// public $next;
//mutator method
public function __set($property, $value) {
$this->$property = $value;
}
//accessor method
public function __get($property) {
if (isset($this->$property)) {
return $this->$property;
} else {
return false;
}
}
// init the properties
function __construct() {
$this->head = null;
// $this->tail = null;
// $this->previous = null;
}
function createLinkList($aList){
if($aList == null || empty($aList)){
//$this = null;
return null;
}
$oPrevious;
foreach ($aList as $data) {
// create node/object
$link = new Node($data);
// first entry, have already created the node, so save a reference to in in the head var
if($this->head == null){
$this->head = $link;
$oPrevious = &$this->head;
}else{ // update the previous nodes link with a pointer to the node createds
$oPrevious->link = $link;
// $this->previous= $link;
$link->link = $this->head;
//$this->head = $link;
}
}
}
}// end class
class node{
private $data = null;
private $link;
//mutator method
public function __set($property, $value) {
$this->$property = $value;
}
//accessor method
public function __get($property) {
if (isset($this->$property)) {
return $this->$property;
} else {
return false;
}
}
/* Node constructor */
function __construct($data)
{
$this->data = $data;
$this->link = null;
}
}
感谢无论谁是低调而不打扰告诉我为什么。这不是一个Q + A网站吗? – atoms
你打算用'$ oPrevious'这一行来实现什么?'实际上? – Victor
我不确定,可能是在想我需要在使用前声明它。我将删除它,谢谢 – atoms