phpfunctionscopeglobal-variablesusort

Can't access global variable inside of a usort() function call


I'm trying to use usort() and leverage a global variable inside its function scope, but without success.

I've simplified my code down to bare bones to show what I mean:

$testglobal = 1;
function cmp($a, $b) {
    global $testglobal;
    echo 'hi' . $testglobal;
}
usort($topics, "cmp");

Assuming the usort() runs twice, my expectations is this will be the output:

hi1hi1

Instead, my output is:

hihi

I've read the manual (http://us.php.net/usort) and I don't see any limitations on accessing global variables. If I assign the usort() to a variable that I echo, it outputs 1, so the usort() is definitely running successfully (plus, there are all those "hi's").


Solution

  • Can't reproduce the "error" and neither can codepad: http://codepad.org/5kwctnDP

    You could also use object properties instead of global variables

    <?php
    class Foo {
        protected $test = 1;
        public function bar($a, $b) {
            echo 'hi' . $this->test;
            return strcmp($a, $b);
        }
    }
    
    
    $topics = array(1,2,3);
    $foo = new Foo;
    usort($topics, array($foo, 'bar'));