dongzhan8620 2013-06-04 03:47
浏览 18
已采纳

(INT)假; 在PHP为什么会这样?

I am reviewing a partner php code and is like:

function query_db($form)
{
   $result = (int)false;    
   try{
    $sqlQuery = " SELECT id_user, id_access, name, email, status FROM users ";
    $sqlQuery .= " WHERE id_access> 0 ";
    if($form->get("limit")){
       $sqlQuery .= " LIMIT ".$form->get("start")." , ".$form->get("registry");
    }           
        $query = $this->db->query($sqlQuery);
    return $query;
   } catch (Exception $e) { 
    $result = (int)false;
   }
    return $result;
}

So at the very begining he uses $result = (int)false;

I was investigating this instruction and found:

A string is converted to false only if it is empty or if it contains the single character 0. If it contains any other data—even multiple zeros—it is converted to true.

When converted to a number or a string, a Boolean becomes 1 if it is true, and 0 otherwise.

So back to the question:

echo 0 + 1; // 1
echo false + 1; // 1
echo 0  > -1; // true
echo false  > -1; // false
echo (int)false > -1; // true

So why in the world he casts it instead of using $result = 0; I mean, I do not understand, maybe it has a deeper meaning and I am not seing this.

Thats why I ask your opinion.

  • 写回答

2条回答 默认 最新

  • doupafu6980 2013-06-04 03:57
    关注

    The answer to "why would it be" is the simple answer: type coercion.

    In your quote, you touched upon the answer:

    When converted to a number or a string, a Boolean becomes 1 if it is true, and 0 otherwise.

    Through type coercion, the (int)false converts the value to 0. If you were to have (int)!false, it would be 1.

    The answer to "why would your friend use this", that's something you'll have to ask him =P. There is no benefit to doing this in this code-block and could be replaced with $result = 0 with zero effect on the outcome.

    In response to a comment, 0 is typically false and 1 is true. When referring to success and error codes, however, it is highly dependent on the system you're interacting with. For instance, in bash, 0 is a "successful" exit code and 1 would mean an error occurred.

    Not answer related:
    In your exact code-block, you can actually remove the $result variable entirely since the code only-ever uses it to return 0 if the query failed; instead, you can just have return 0; at the end - or return false; if you'd prefer dealing directly with boolean values.

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

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么