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条)

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大