0

可能重复:
无法访问 usort 函数中的全局变量?

我已经经历过这个问题不止一次了,这次我不知道如何解决它。

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

为什么这不显示带有“> hej <”的警报框,对我来说它显示“> <”。

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

4

1 回答 1

3

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

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

<?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'));
于 2012-08-21T13:43:00.490 回答