Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is_null function not working properly in my if statement

Tags:

oop

php

logic

I have an if statement that detects if an user is logged in and belongs to a certain division. It really is quite simple.

There is a Permissions.php class, that returns the User object if logged in or NULL.

protected $user = NULL;
...
public static function instance() {
  if(!self::$instance) {
    self::$instance = new Permissions();
  }
  return self::$instance;
}
...
public function get_user() {
  return $this->user;
}

There is then the user.php class, that has functions to return what division they are in:

public function is_manager() {
  return $this->is_manager;
}

So I should be able to do the following:

if(Permissions::instance()->get_user()->is_manager())

But of course that might throw a warning about NULL objects, so I thought you could do the following:

if( ( ! is_null( Permissions::instance()->get_user() ) ) &&
    ( Permissions::instance()->get_user()->is_manager() ))

Which should check for null and if not, it should evaluate the other half of the if statement, but PHP for some reason, evaluates all of it and still complains about a NULL object (when the user is not logged in).

So then I broke the if statement up into a nested if statement, and PHP still complained about the null object, which led me to believe that the is_null method wasn't working as expected.

This worked in the end:

if (Permissions::instance()->get_user() != NULL) {
  if(Permissions::instance()->get_user()->is_manager()){
    ...
  }
}

My question is, why did my code with the is_null function not work?


Upon further testing, thanks to some of your great comments, it turns out that get_user() wasn't returning NULL, but (bool)false (from var_dump). Why is this strange behaviour exhibited? My class clearly sets it to NULL at the top and the function returns the variable as false?

like image 326
Husman Avatar asked Mar 13 '13 09:03

Husman


1 Answers

Because != does not check the type (null is a type) and get_user() returned something like an empty string or false (see PHP type comparison table).

Check the output of:

var_dump(Permissions::instance()->get_user());
like image 71
Fabian Schmengler Avatar answered Sep 30 '22 14:09

Fabian Schmengler