duanpei8518 2012-09-10 19:02
浏览 32
已采纳

在PHP中设置并验证IF中的返回值

Could I do this in PHP?

if ($Var = $this->test1() == true) {
    var_dump($Var);
}

public function test1() {
    return true;
}

It echoes true, but I'm not sure if this is the correct way to check such return values.

  • 写回答

4条回答 默认 最新

  • drmq16019 2012-09-10 19:34
    关注

    You can but there is 2 things you should be aware of :

    When you do something like :

    if ($Var = $this->test1() == true) {
    

    The operators are confusing :

    • do you want to do $this->test1() == true and store result $var
    • do you want to do $var = $this->test1() and compare it with true

    In your case, $this->test1() returns true so it does not matter. But if we change your code a bit :

    if ($Var = $this->test1() == 5) {
        var_dump($Var);
    }
    
    public function test1() {
        return 3;
    }
    

    Someone who read your code will not understand if you want to store $this->test1() in $Var (so, make 3 in var) or if you want to put result of comparison $this->test1 == 5 in $Var (false).

    What remains in $Var at the end may be a very good question at the PHP 5.3 Certification but not in a useful case.

    To avoid mistakes, uses parenthesis :

    if (($var = $this->test1()) == true) {
    

    You should take care of types :

    I give you an example of what could return something castable to true :

    function test1() { return true; }
    function test2() { return 3; }
    function test3() { return 3.42; }
    function test4() { return "x"; }
    function test5() { return array('x'); } // array() == true returns false
    function test6() { return new stdClass(); }
    
    echo test1() == true;
    echo test2() == true;
    echo test3() == true;
    echo test4() == true;
    echo test5() == true;
    echo test6() == true;
    
    // outputs 111111 (1 = true)
    

    To avoid mistakes, you should use === operator. Your final piece of code becomes :

    if (($var = $this->test1()) === true) {
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。