tags:

views:

389

answers:

3

This example is from php.net:

<?php
function Test()
{
    static $a = 0;
    echo $a;
    $a++;
}
?>

And this is my code:

function getNextQuestionID()
{
 static $idx = 0;
 return $idx++;
}

And I use it in JavaScript:

'quizID=' + "<?php echo getNextQuestionID(); ?>"

Returns 0 everytime. Why?

+5  A: 

I believe you misunderstand what static vars do. Try this code and you may understand better:

echo getNextQuestionID() . ", " getNextQuestionID() . ", " getNextQuestionID();

And you will see what I mean.

The static var only lives as long as the script does.

The reason it is returning 0 on the first run instead of 1 is because you are using the postfix operator $var++ instead of the prefix version - ++$var. The difference is is that the increment only gets applied when using the postfix operator after the function returns - but if you use the prefix operator it is applied before the function returns.

nlaq
Sorry I meant returns 0 everytime. I know the difference between post and pre-increment.
SyaZ
A: 

If you want your data to persist across multiple pages, you need to use sessions.

Even using $_SESSION in the above example will give the same result, ie the variable gets reset at end of script execution. Kinda weird for a session variable.
SyaZ
+1  A: 
session_start();
function getNextQuestionID()
{
    if (!isset($_SESSION['qNo'])) {
        $_SESSION['qNo'] = 0;
    } else {
        $_SESSION['qNo']++;
    }

    return $_SESSION['qNo'];
}
Tom Haigh