1

If i have an if statement that relies on one of two methods returning false, would both methods run if the first methods returns false. Example:

class myClass {
    public function functPublic()
    {
        if(!$this->funct1() || !$this->funct2()){
            print('test');
        }
    }

    private function funct1()
    {
        // complex code here
        return false;
    }

    private function funct2()
    {
        // complex code here
        return false;
    }
}

Would the above code execute the funct2() method even though it has already recieved a false from the funct1() method?

1
  • 2
    Simplest way to test for yourself is to add a die("second funct called"); in your function. Commented Jun 12, 2015 at 7:36

4 Answers 4

3

If the first condition is evaluated to true, then the second will not be called. A simple way to test php things like that is to use phpfiddle.org Or make a php script yourself, or run it command line.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the tip. Using the methods you suggested, In this case, funct2() is never called.
Yep, basically, in order to optimise code processing, if you have multiple condition, and specifically OR conditions, the interpreter stop checking after the first TRUE found. That way it saves time, cpu, ram etc :)
1

PHP uses short-circuit evaluation.

In all these cases, foo() is never called.

$a = (false && foo());
$b = (true  || foo());
$c = (false and foo());
$d = (true  or  foo());

So with

function funct1() {
    return false;
}

thus

if (!$this->funct1() || !$this->funct2())

is

if (!false || !$this->funct2())

is

if (true || !$this->funct2())

means that $this->funct2() is never called.

Ref: http://php.net/manual/en/language.operators.logical.php

Comments

0

No

If first is true then not require to evaluate second.

TRUE if either $a or $b is TRUE.

Read here

Comments

0

using OR, the first check is performed. If that evaluates to true, the second one is not run. Only if the first one evaluates as false would the second one be called. If you need both to run, use AND instead.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.