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:


Instead, my output is:


I've read the manual ( 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").


  • Can't reproduce the "error" and neither can codepad:

    You could also use object properties instead of global variables

    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'));