2017-02-12 87 views
0

我有一個對象的屬性,我沒有定義,但沒有下面的檢查返回有利於對象爲null。什麼時候是一個PHP對象爲空?

僅當我們將它指定爲null時,該對象才爲null。我嘗試了幾次,並尋找其他替代方法,但沒有一個能夠說明對象是空的而非對立的。那麼我們如何檢查一個對象是否爲空,或者下面的所有方法都是錯誤的呢?

或者是一個永遠不會爲空的對象,因爲即使它們沒有設置,它也會保留屬性。

class LinkedList implements DataStructure { 


    public $head; 

    public function __construct(){ 
     $this->head = new Node; 
     $this->tail = new Node; 

     //checking all posibilities i am aware of 
     echo "are you an object ? ".gettype($this->head); 

     echo "<br/>are you null ? ".is_null($this->head); 
     echo "<br/>are you empty ? ".empty($this->head); 
     echo "<br/>are you null ? ". ($this->head === null); 
     echo "<br/>what is your count ? ".count($this->head); 
     echo "<br/>maybe you are not set ? ".isset($this->head); 

    } 
} 

這是我的節點類..如果它可以幫助你們幫我

class Node { 

    public $next; 
    public $file; 
    public $folder; 
    public $parentDirectory; 

} 

上述代碼的輸出是:

are you an object ? object 
are you null ? 
are you empty ? 
are you null ? 
what is your count ? 1 
maybe you are not set ? 1 

另外一個var_dump($this->head)返回此

object(App\Library\DataStructures\Node)#202 (4) { 

    ["next"]=> 
    NULL 

    ["file"]=> 
    NULL 

    ["folder"]=> 
    NULL 

    ["parentDirectory"]=> 
    NULL 

} 

謝謝。

回答

2

看一看PHP類型: http://php.net/manual/en/language.types.php

object是一個類型,而null是另一種類型。

這裏您將$this->head設置爲objectNode。儘管Node對象內部發生了什麼,但它仍然是object

如果您設置了this->head = null,那麼只有它會被認爲是null

+0

謝謝你的信息。但是,如果是這樣的話,檢查一個對象是否只被聲明並且沒有定義它的屬性的正確方法是什麼? –

+0

你可以檢查它是否是'$ this-> head === new Node()'。 – zed

+0

好的,謝謝 –

相關問題