Search code examples
phpfunctionif-statementexecute

Why is the foo() function executed while not having been called?


I'm kind of new to PHP so please excuse the simplicity of my question in case it was, I have a function foo() that always returns true, now my question is that while I have only checked the true being of foo() and not called the foo() function directly, how possibly did it execute then? And is only PHP like this or it is the same say in JavaScript?

 $x = 10;
function foo() {
    global $x;
    if($x = 10) {
        return true;
    }
    return false;
}

if(foo()) {
    echo 'Done foo() function!';
} else {
    echo 'Not done foo() function...';
}

Solution

  • you did called foo in if(foo()) this line. Essentially what you did in this line is called foo and checked its return value with if. If you want to check if foo function is executed or not you can keep a flag as global variable and and set it to true in the function somewhere like this

    $foo_executed = false;
    function foo (){
        global $foo_executed;
        // your code here
        $foo_executed = true;
    }
    
    //execute foo
    foo();
    if ($foo_executed){
       echo "foo executed";
    }
    

    This behavior is also common in other programming languages. You can follow this tutorial to learn more about functions. good luck!

    https://www.youtube.com/watch?v=HvxQww-7NGA