无法访问 usort() 函数调用内部的全局变量

发布于 2024-07-22 20:29:08 字数 573 浏览 5 评论 0原文

我尝试使用 usort() 并在其函数范围内利用全局变量,但没有成功。

我已将我的代码简化为简单的代码以显示我的意思:

$testglobal = 1;
function cmp($a, $b) {
    global $testglobal;
    echo 'hi' . $testglobal;
}
usort($topics, "cmp");

假设 usort() 运行两次,我的期望是这将是输出:

hi1hi1

相反,我的输出是:

hihi

我已阅读手册(http://us.php.net/usort),我没有看到任何访问全局变量的限制。 如果我将 usort() 分配给我回显的变量,它会输出 1,因此 usort() 肯定运行成功(另外,还有所有这些“hi” ”)。

I'm trying to use usort() and leverage a global variable inside its function scope, but without success.

I've simplified my code down to bare bones to show what I mean:

$testglobal = 1;
function cmp($a, $b) {
    global $testglobal;
    echo 'hi' . $testglobal;
}
usort($topics, "cmp");

Assuming the usort() runs twice, my expectations is this will be the output:

hi1hi1

Instead, my output is:

hihi

I've read the manual (http://us.php.net/usort) and I don't see any limitations on accessing global variables. If I assign the usort() to a variable that I echo, it outputs 1, so the usort() is definitely running successfully (plus, there are all those "hi's").

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

请持续率性 2024-07-29 20:29:08

如果使用超级全局 访问变量是否有效$GLOBALS 数组?

$testglobal = 1;
function cmp($a, $b) {
    echo 'hi' . $GLOBALS['testglobal'];
}
usort($topics, "cmp");

Does it work if you access the variable using the super-global $GLOBALS array?

$testglobal = 1;
function cmp($a, $b) {
    echo 'hi' . $GLOBALS['testglobal'];
}
usort($topics, "cmp");
你好,陌生人 2024-07-29 20:29:08

无法重现“错误”,键盘也无法重现: http://codepad.org/5kwctnDP

您可以也使用对象属性而不是全局变量

<?php
class Foo {
    protected $test = 1;
    public function bar($a, $b) {
        echo 'hi' . $this->test;
        return strcmp($a, $b);
    }
}


$topics = array(1,2,3);
$foo = new Foo;
usort($topics, array($foo, 'bar'));

Can't reproduce the "error" and neither can codepad: http://codepad.org/5kwctnDP

You could also use object properties instead of global variables

<?php
class Foo {
    protected $test = 1;
    public function bar($a, $b) {
        echo 'hi' . $this->test;
        return strcmp($a, $b);
    }
}


$topics = array(1,2,3);
$foo = new Foo;
usort($topics, array($foo, 'bar'));
舟遥客 2024-07-29 20:29:08

我在问题中输入的代码被放入 bbPress 的模板中,bbPress 是 WordPress 的近亲论坛。 一位朋友告诉我,“有时,如果您在定义变量之前没有全局变量,PHP 会表现得很奇怪,具体取决于代码执行时的嵌套程度 - bbPress 在模板输出时会执行一些复杂的包含操作”。

所以我尝试了一下,它起作用了:

global $hi123;
$hi123 = ' working ';

我正在回答我自己的问题,以防像我这样的另一个白痴在谷歌搜索中发现这个。 :-)

不过,我将接受 VolkerK 的回答,因为对象解决方法非常聪明。

The code I put in my question was dropped inside a template on bbPress, which is the forum cousin to Wordpress. A friend told me that "Sometimes PHP will act weird if you don't global a variable before you define it, depending on how nested the code is when it's executed - bbPress does some complex includes by the time the template outputs".

So I tried that and it works:

global $hi123;
$hi123 = ' working ';

I'm answering my own question in case another idiot like me finds this in a Google search. :-)

I'm going to accept VolkerK's answer, though, because the object workaround is pretty clever.

平生欢 2024-07-29 20:29:08

它从 php 5.2.4 开始工作

$testglobal = ' WORKING ';
$topics = array('a','b','c');      
function cmp($a, $b) {
    global $testglobal;
    echo 'hi' . $testglobal;
}
usort($topics, "cmp");
// hi WORKING hi WORKING 

It is working as of php 5.2.4

$testglobal = ' WORKING ';
$topics = array('a','b','c');      
function cmp($a, $b) {
    global $testglobal;
    echo 'hi' . $testglobal;
}
usort($topics, "cmp");
// hi WORKING hi WORKING 
围归者 2024-07-29 20:29:08

不要将变量定义为 global 或访问 $GLOBALS 作为解决方法 - 这些是现代应用程序中的代码味道,并且通常会恶化变量的范围控制。

对于 PHP7.4 以下的应用程序(并且在 2023 年,您不应该使用过时的版本),您可以通过函数签名后的 use ($theGlobalVariable) 来允许访问全局变量。

对于使用 PHP7.4 或更高版本的应用程序,“箭头函数语法”允许在函数作用域内读取全局变量。

以下演示了如何在 usort() 调用内部利用全局范围的查找数组。 这是一个非常实用的示例,通常可以在专业代码库中找到来执行自定义排序。

代码:(演示

$lookup = [
    'foo' => 1,
    'bar' => 2,
    'baz' => 3,
    'fizz' => 4,
    'buzz' => 5,
];

$array = ['buzz', 'foo', 'baz'];
// sort $array ascending according to its mapped value
usort($array, fn($a, $b) => $lookup[$a] <=> $lookup[$b]);
var_export($array);

输出:

array (
  0 => 'foo',
  1 => 'baz',
  2 => 'buzz',
)

Do not define variables as global or access $GLOBALS as a work around -- these are code smells in modern applications and deteriorate the scoped control of variables in general.

For applications below PHP7.4 (and in 2023, you shouldn't be using outdated versions), you can permit access to global variables via use ($theGlobalVariable) after the function signature.

For applications enjoying PHP7.4 or higher, "arrow function syntax" allows a global variable to be read inside the function scope.

Here is a demonstration of leveraging a globally-scoped lookup array from inside of a usort() call. This is a very practical example that can be commonly found in professional codebases to perform a custom sort.

Code: (Demo)

$lookup = [
    'foo' => 1,
    'bar' => 2,
    'baz' => 3,
    'fizz' => 4,
    'buzz' => 5,
];

$array = ['buzz', 'foo', 'baz'];
// sort $array ascending according to its mapped value
usort($array, fn($a, $b) => $lookup[$a] <=> $lookup[$b]);
var_export($array);

Output:

array (
  0 => 'foo',
  1 => 'baz',
  2 => 'buzz',
)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文