0

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.

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

thank you for the information. But if so what is the proper way of checking if an object has only been declared and none of its properties have been defined ?
You can just check if it is $this->head === new Node().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.