2012-01-17 34 views
1

我正在創建鏈接列表類,並且對引用對象有一些困惑。PHP:引用對象的鏈表實現問題?

按照我的理解默認情況下,對象是通過引用複製的。 $ Obj1 = $ Obj2。 $ Obj1是$ Obj2的別名。

有人能指出哪一個在鏈表實現中是正確的。

$firstNode->next = $this->first;---> seems to be correct 
      or 
$firstNode->next =& $this->first; 

$this->first = $firstNode;-----> seems to be correct as $firstNode is an object 
      or 
$this->first = & $firstNode; 

代碼:

class Node { 
    public $element; 
    public $next; 

public function __construct($element){ 
    $this->element = $element; 
    $this->next = NULL; 
    } 
} 

class Linklist { 

    private $first; 
    private $listSize; 

public function __construct(){  
    $this->first = NULL; 
    $this->listSize = 0; 
} 

public function InsertToFirst($element){ 
    $firstNode = new Node($element); 
    $firstNode->next = $this->first; // or $firstNode->next =& $this->first; 
    $this->first = $firstNode; // or $this->first = & $firstNode; 
} 
+1

(如果這不是作業)爲什麼你會在PHP中創建一個鏈表? – erenon 2012-01-17 15:09:34

回答

2

在PHP中,你不需要使用引用賦值(別名/ &)爲您的鏈表,如果每個節點都是一個對象本身nextfirst是的對象節點類型也是如此。

請參閱Objects and References in the PHP Manual瞭解詳情。

+0

你的意思是$ this-> first = $ firstNode;是正確的?不需要添加&在對象前面? – 2012-01-17 15:11:59

+0

@Praveen:正確地表達它的工作。您應該爲這些屬性編寫getter和setter方法,並確保始終分配正確的類型。 - 在答案中增加了一個有用的鏈接。 – hakre 2012-01-17 15:13:17

+0

我看到一個代碼http://www.codediesel.com/php/linked-list-in-php/,它使用&分配對象,所以我問了這個問題 – 2012-01-17 15:14:46