答案很简单:不要使用全局变量。
如果要访问该变量并更改该变量的值,请通过引用将其作为参数传递:
<?php
$testing = "hej";
function compare($b, $a, &$testing) {
$testing = "def";
}
compare(1, 2, $testing);
echo $testing; // result: "def"
如果您只想要该值,请按值传递:
<?php
$testing = "hej";
function compare($b, $a, $testing) {
$testing = "def";
}
compare(1, 2, $testing);
echo $testing; // result: "hej"
更新:
另一种选择是将对象传递给usort()
数组:
<?php
class mySort {
public $testing;
public function compare($a, $b) {
echo '<script>alert(\'>'.$this->testing.'<\');</script>';
}
}
$data = array(1, 2, 3, 4, 5);
$sorter = new mySort();
usort($data, array($sorter, 'compare'));