dpnzf48660 2011-02-04 00:36
浏览 67
已采纳

在php中将变量强制转换为布尔值的最佳方法是什么?

I was reading this question and saw this line:

if ($a == $b) { return true } else { return false }

And it led me to wondering, what is the best way to cast a variable of unknown type (could be string, could be int; who knows? who cares?) to a boolean?

Of course, if ($var) { return true; } else { return false; } would do the trick, but I think return $var ? true : false; is probably better.

For that matter:

  • return $var && true
  • return $var || false
  • return !empty($var)

are all probably better, but is there a best way to cast to bool? More importantly, what makes it best?

Edit to clarify:

This wasn't written with the intention of being a comprehensive list of the ways to cast to a boolean. My question is specifically on explicit casting. Before I learned about empty I used isset($var) && $var as it would prevent errors from being thrown on undeclared variables. Now i use !empty($var) as it's faster to type.

!empty has the (dis)advantage of not throwing any E_NOTICE errors when the variable isn't defined. This could be considered good if you're checking $_GET or $_SESSION variables, for the majority of other variables, I suppose this may be considered bad as it would hide issues where a variable is uninitialized where it should have been initialized.

I was curious as to whether other developers have another way of doing things that I hadn't known about.

  • 写回答

5条回答 默认 最新

  • dqab0824 2011-02-04 00:46
    关注

    The two ways are:

    1. Explicit cast:

      This is when you explicitly cast the variable using the literal cast operator (bool).

      return (bool) $expression;
      
    2. Implicit cast (using operators):

      This is where the type is inferred from the expression. In PHP, this includes logical operators and comparison operators, and any function/language construct that expects a boolean such as if and while:

      return !!$expression;
      

      or

      return $expression == true;
      

      or

      return $a == $b;
      

      or

      return $a > 1;
      

      or

      if ($a)
      

    All methods will fall into one of those two categories.

    My suggestion is that if you use any operators (==, !=, >, etc), don't bother casting. But if you're just returning a variable, then cast explicitly...

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 关于大棚监测的pcb板设计
  • ¥20 sim800c模块 at指令及平台
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计