dougan4663 2016-09-22 14:31 采纳率: 0%
浏览 40
已采纳

empty()如何使用布尔表达式?

A guy learning PHP sent me some code that has me scratching my head. He's getting $_POST input, putting it in variables, and then:

if( !empty($id && $name && $email) ) {
    //do something
}

My first inclination was that passing multiple variables as an argument would throw an error, but it evaluates successfully. Am I incorrect that empty() should NOT take a boolean expression? Or - if I'm right - why does it work?

  • 写回答

1条回答 默认 最新

  • dongxuanyi3406 2016-09-22 14:45
    关注

    You can pass an expression to empty rather than a variable (since PHP 5.5), but with an expression like that you lose half of the benefit of using empty. empty checks that variables are set as well as evaluating their "truthiness". When you give it an expression like that, the individual variables within the expression are not checked to exist by empty. The expression is just evaluated as a boolean.

    So if you used separate empty checks, you would get the check that the variables exist as well as the check that they are != false

    if(!empty($id) && !empty($name) && !empty($email))
    

    But when you use

    if (!empty($id && $name && $email))
    

    You will still get into the if block if all the variables are set and have non-false values, but you'll get undefined variable notices if any of them are not set. It's basically the same thing as not using empty at all, like this:

    if ($id && $name && $email)
    

    But if your guy is setting these variables from $_POST, they will be set, (if they weren't in $_POST he'd get undefined index warnings at that point) and the empty here is pointless anyway.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)