Search code examples
phpif-statementbooleanvariable-assignmentcomparison-operators

PHP comparison operators and statements of the form if (!foo())


Here is my little script, and from writing it I've learned that I've no idea how PHP handles variables...

<?php 
$var = 1;

echo "Variable is set to $var <br />";

if (!foo()) echo "Goodbye";

function foo()
{
    echo "Function should echo value again: ";

    if ($var == 1)
    {
        echo "\$var = 1 <br />";
        return true;
    }

    if ($var == 2)
    {
        echo "\$var = 0 <br />";
        return false;
    }
}     
?>

So, here is how I thought this script would be interpreted:

  • The statement if (!foo) would run foo(). If the function returned false, it would also echo "Goodbye" at the end.

  • The function foo() would check whether $var == 1 or 2 (without being strict about datatype). If 1 it would echo "Function should echo value again: 1", and if 2, it would echo the same but with the number 2.

For some reason both if statements inside foo() are being passed over (I know this because if I change the first if statement to if ($var != 1), it passes as true, even if I declared $var = 1.

What's happening here? I thought I had all this down, now I feel like I just went backwards :/


Solution

  • The function doesn't know what $var is. You'd have to pass it in, or make it global:

    function foo() {
      global $var;
      /* ... */
    }
    

    Or

    $var = 1;
    if ( !foo( $var ) ) echo "Goodbye";
    
    function foo ( $variable ) {
      /* Evaluate $variable */
    }
    

    By the way, it's almost always better to avoid global variables. I would encourage you to go the latter route and pass the value into the function body instead.