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 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line