sujan basnet
sujan basnet

Reputation: 300

When is a php object null?

I have an object whose properties I haven't defined and yet none of the below checks return in favor of object being null.

Is an object only null when we assign it as null. I tried few and searched for other alternatives but none of them tell that the object is null rather opposite. So how do we check if an object is null, or all of the below ways are false ?

Or is an object never null since it holds properties even though they are not set.

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);

    }
}

this is my Node class .. if it helps you guys help me

class Node {

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

}

The output of the above code is :

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

Also a var_dump($this->head) returns this

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

  ["next"]=>
  NULL

  ["file"]=>
  NULL

  ["folder"]=>
  NULL

  ["parentDirectory"]=>
  NULL

}

Thank you.

Upvotes: 0

Views: 232

Answers (1)

zed
zed

Reputation: 3267

Have a look at PHP types: http://php.net/manual/en/language.types.php

object is a type, and null is another type.

Here you are setting $this->head to an object Node. Nonetheless of what happens inside Node object, it is still an object.

If you set this->head = null, only then it would be considered of type null.

Upvotes: 2

Related Questions