无法访问函数中的全局变量


Cant access global variable in function

可能重复:
可以';是否访问usort函数内部的全局变量?

我已经不止一次遇到这个问题了,这次我不知道该怎么解决

$testing = "hej";
function compare($b, $a)
{
    global $testing;
    echo '<script>alert(''>'.$testing.'<'');</script>';
}

为什么这没有显示一个带有">hej<"的报警框,对我来说,它显示的是"><

此外,这是从uasort调用的函数,作为第二个参数。

答案很简单:不要使用全局变量

如果您想访问该变量并更改该变量的值,请通过引用将其作为参数传递:

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