0

重複の可能性:
usort 関数内のグローバル変数にアクセスできませんか?

私はこの問題を何度も経験しましたが、今回はそれを回避する方法がわかりませんでした。

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

アラート ボックスに ">hej<" が表示されないのはなぜですか。私の場合は "><" と表示されます。

uasortまた、これは第 2 パラメーターとして呼び出される関数です。

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 に答える