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:
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'));
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.
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
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");