can't access global variables inside a usort function?

前端 未结 4 1233
终归单人心
终归单人心 2021-01-15 16:32

I\'m trying to do a usort in PHP, but I can\'t access global variables inside a usort function.

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

相关标签:
4条回答
  • 2021-01-15 16:43

    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'));
    
    0 讨论(0)
  • 2021-01-15 16:49

    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.

    0 讨论(0)
  • 2021-01-15 16:55

    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 
    
    0 讨论(0)
  • 2021-01-15 16:59

    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");
    
    0 讨论(0)
提交回复
热议问题