Nick Bolton
Nick Bolton

Reputation: 39550

Should we declare and check null or use isset in PHP?

Which approach is considered best practice?

Declare and check null...

class Foo {
  $bar = null;
  function test() {
    return $this->bar != null;
  }
}

Or, isset(...)...

class Foo {
  function test() {
    return isset($this->bar);
  }
}

Upvotes: 0

Views: 71

Answers (1)

deceze
deceze

Reputation: 522081

It makes a lot more sense to declare all the properties your class has, and check what their values are. It gives you a clear sense of what the class can do and what values it may have, rather than guessing every step of the way what property some other function may be looking for sometime later.

class Foo {
  protected $bar = null;
  public function test() {
    return $this->bar !== null;
  }
}

Note the !== check here; if you'd just use != the condition would be true for a number of other values besides just null.

It really is the exact same thing as any other variables in your code: you should always initialise any and all variables your code will work with, and then just worry about their values. isset should be used exclusively for cases where you have no control over the existence of a variable, e.g. as is the case for user input. For any other situation where you have perfect control over the existence or non-existence of your variable, opt for explicitly initialising them.

Upvotes: 3

Related Questions