sk8terboi87  ツ
sk8terboi87 ツ

Reputation: 3457

Is it right to use empty() function for checking an object is null?

Say,

$obj = $this->someFunc(); // this returns an object

if(empty($obj)){ 
    // suppose $obj is null, it does works correctly
}

In http://php.net/manual/en/function.empty.php, empty() is only used for variables and arrays.

But, is it the correct way?

Upvotes: 4

Views: 16813

Answers (6)

Bas Matthee
Bas Matthee

Reputation: 116

Just check:

if ($obj === null) {
   // Object is null
} else {
   // Object isn't null
}

Which is also possible to do with:

if (is_null($obj)) {
    // Object is null
}

Upvotes: 2

kingdomcreation
kingdomcreation

Reputation: 659

An object with no properties are not empty anymore as of PHP 5 I use isset a lot to chek that it has a value and that that value isnt NULL

Upvotes: 0

Sumit Bijvani
Sumit Bijvani

Reputation: 8179

You can use is_null() for this

Upvotes: 0

Yogesh Suthar
Yogesh Suthar

Reputation: 30488

use is_null for checking object is null or not.

Upvotes: 0

ceth
ceth

Reputation: 754

php has the function is_null() to determine whether an object is null or not: http://php.net/manual/en/function.is-null.php

Upvotes: 11

John Conde
John Conde

Reputation: 219804

null will cause empty() to return true. However, if you're checking to see if that value is actually null, is_null() is better suited for the job.

Upvotes: 3

Related Questions