Can't access global variables inside the usort function?
I am trying to do usort in PHP, but I cannot access the globals inside the usort function.
I've simplified my code to the bare bones to show what I mean:
$testglobal = 1;
function cmp($a, $b) {
global $testglobal;
echo 'hi' . $testglobal;
}
usort($topics, "cmp");
Assuming usort works twice, my expectation is the output:
hi1hi1
Instead, my output is:
hihi
I have read the manual ( http://us.php.net/usort ) and I don't see any restrictions on accessing global variables. If I assign usort to a variable that I echo, it outputs 1, so usort definitely works successfully (plus, there are all those "hi").
Am I doing something incredibly stupid here? If not, is there a workaround?
a source to share
Can't reproduce the "bug" and also can't encode: http://codepad.org/5kwctnDP
You can 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'));
a source to share
The code I put in my question has been removed inside the bbPress template, which is the forum cousin to Wordpress. One friend told me that "Sometimes PHP will act weird if you don't use a global variable before you define it, depending on how the code is nested when it is executed - bbPress is doing some complex set by the time template exit ".
So I tried this and it works:
global $hi123;
$hi123 = ' working ';
I am answering my own question if another idiot like me finds this in a google search. :-)
I'm going to accept VolkerK's answer though, because the object's workaround is pretty clever.
a source to share