views:

499

answers:

1

Ok, I fear that this is just me having forgotten some small stupid thing about PHP, but I just can't seem to figure out what is going on here.

Test code:

<?php header('Content-Type: text/plain');

$closingDate     = mktime(23, 59, 59, 3, 27, 2009);

function f1()
{
    return time() > $closingDate;
}
function f2()
{
    return time() < $closingDate;
}

printf('    Time: %u
Closing: %u

t > c: %u
f1   : %u

t < c: %u
f2   : %u', 
    time(), 
    $closingDate, 
    time() > $closingDate,
    f1(), 
    time() < $closingDate,
    f2());

The problem is that the output doesn't make sense to me at all. And I don't get why it turns out like it does:

Time: 1235770914
Closing: 1238194799

t > c: 0
f1   : 1

t < c: 1
f2   : 0

Why doesn't the function output the same result as the code inside the function?? What am I not getting here? Have I looked myself completely blind on my own code? What is going on?

+7  A: 

You're not passing $closingDate to the functions. They are comparing time against null.

Try:

function f1()
{
    global $closingDate;
    return time() > $closingDate;
}
function f2()
{
    global $closingDate;
    return time() < $closingDate;
}

Or:

// call with f1($closingDate);
function f1($closingDate)
{
    return time() > $closingDate;
}

// call with f2($closingDate);
function f2($closingDate)
{
    return time() < $closingDate;
}

Check out the PHP documentation on variable scoping.

Paolo Bergantino
oooh. The global thing?
Svish
Yup, the global thing.
Paolo Bergantino
knew there was something stupid I had forgotten :p too long since I have programmed PHP... thank you =) This fixed it: global $closingDate;
Svish
It would probably be better practice to pass $closingDate as a parameter to the functions instead of using the global keyword. So your declaration would be: function f1($closingDate). If you were to modify the value it could lead to unexpected results in when other functions try to access it.
robmerica