-3

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...';
}
christy
  • 3
  • 5
  • 3
    `$nextFoo = foo();` ... executes the function. What did you expect? – brombeer Aug 21 '21 at 13:49
  • 2
    fyi, `if($x = 10) {` _assigns_ a value, use `==` or `===` to compare values. If you set `$x = 12;` outside of your function it will also `return true`. – brombeer Aug 21 '21 at 13:52
  • erm ... why is this tagged javascript? – Bravo Aug 21 '21 at 13:52
  • Are you asking about PHP or JavaScript? – evolutionxbox Aug 21 '21 at 13:52
  • @brombeer Oh, I thought $nextFoo only held the function `foo()` in itself, I deleted the `$nextFoo = foo();` line and only passed the `foo()` in the condition of the if statement, and `foo()` still executes, now how did it execute? – christy Aug 21 '21 at 13:55
  • 1
    Don't change your question, add any changes to it. The code would give you a "_Warning: Undefined variable $foo..._" now, `$foo` is not set anywhere – brombeer Aug 21 '21 at 13:58
  • 1
    Please stop changing the code so drastically. You're making the comments obsolete and the answers too. – evolutionxbox Aug 21 '21 at 14:01
  • @brombeer Yes, typing `$foo` instead of `foo()` was a typo, but now where is `foo()` called to be executed? – christy Aug 21 '21 at 14:02
  • 1
    `if(foo()) {` executes the function, might want to find a basic tutorial on how PHP/functions work, SO is for specific coding problems, not teaching the basics – brombeer Aug 21 '21 at 14:03
  • @evolutionxbox Alright I won't change it again since I did my final edit. – christy Aug 21 '21 at 14:04

1 Answers1

-1

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

Nazmul Ahasan
  • 34
  • 1
  • 8