-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