在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.

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

Yes you can, but write:

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

To be safe and to alert the reader there is something going on.

I wouldn't advise you to do this though, but in some cases this is acceptable; such as a complex if-else tree where lazy execution is desirable.

if (($result = slow_process()) !== false) {
    return $result;
} else if (($result = slow_process1()) !== false) {
    return $result;
} else if (($result = slow_process2()) !== false) {
    return $result;
} else if (($result = slow_process3()) !== false) {
    return $result;
}

This is overly simplified, but these situations do occur.

The == true part is unnecessary. What you have is valid syntax, but some find it confusing. You can always do:

$Var = $this->test1();
if ($Var) { ...

Just decide on the standard with your development team.

You can also do:

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

public function test1() {
    return true;
}