tags:

views:

291

answers:

4

I'm trying to do a usort in PHP, but I can't access global variables inside a usort function.

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").

Am I doing something incredibly stupid here? If not, is there a workaround?

A: 

Does it work if you access the variable using the super-global $GLOBALS array?

$testglobal = 1;
function cmp($a, $b) {
    echo 'hi' . $GLOBALS['testglobal'];
}
usort($topics, "cmp");
tj111
No, I tried that, but thank you for suggesting it! :-)
bobbyh
+1  A: 
VolkerK
A: 

It is working as of php 5.2.4

$testglobal = ' WORKING ';
$topics = array('a','b','c');      
function cmp($a, $b) {
    global $testglobal;
    echo 'hi' . $testglobal;
}
usort($topics, "cmp");
// hi WORKING hi WORKING
Lepidosteus
A: 

The code I put in my question was dropped inside a template on bbPress, which is the forum cousin to Wordpress. A friend told me that "Sometimes PHP will act weird if you don't global a variable before you define it, depending on how nested the code is when it's executed - bbPress does some complex includes by the time the template outputs".

So I tried that and it works:

global $hi123;
$hi123 = ' working ';

I'm answering my own question in case another idiot like me finds this in a Google search. :-)

I'm going to accept VolkerK's answer, though, because the object workaround is pretty clever.

bobbyh