doxd96148 2013-03-13 09:59
浏览 34
已采纳

is_null函数在我的if语句中无法正常工作

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?

  • 写回答

1条回答 默认 最新

  • dongyingtang3803 2013-03-13 10:14
    关注

    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());
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3