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

时间:2012-08-21 13:39:48

标签: php

  

可能重复:
  can't access global variables inside a usort function?

我现在经历过这个问题已经超过一次,而这次我无法弄清楚如何绕过它。

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

为什么这不显示带有“&gt; hej&lt;”的警告框,对我来说它显示“&gt;&lt;”。

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

1 个答案:

答案 0 :(得分: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'));
相关问题