开发者

Availability of method vars within a sub-function

开发者 https://www.devze.com 2023-02-10 01:46 出处:网络
Referencing a method parameter variable from within a sub-function of that method doesn\'t seem to work even when global is specified.

Referencing a method parameter variable from within a sub-function of that method doesn't seem to work even when global is specified.

public function sortArray(&$array, $keyT开发者_运维百科oCompare){// BOOL sortArray( ARR &$array, STR $keyToCompare )
    function cmpVals($pairA, $pairB){
        global $keyToCompare;
        return strcmp($pairA[$keyToCompare], $pairB[$keyToCompare]);
    }
    return uasort($array, 'cmpVals');
}

Is it even possible to reference a method parameter from within a sub-function? If so... how?

For my specific example above I realise I could use a closure to achieve the same goal but I don't want the script to be PHP 5.3 dependent.


Any reason you can't make it static?

class YourClassName {
    public static $keyToCompare;
    public function sortArray(&$array, $keyToCompare){// BOOL sortArray( ARR &$array, STR $keyToCompare )
        self::$keyToCompare = $keyToCompare;
        function cmpVals($pairA, $pairB){
            $keyToCompare = YourClassName::$keyToCompare;
            return strcmp($pairA[$keyToCompare], $pairB[$keyToCompare]);
        }
        return uasort($array, 'cmpVals');
    }
}


You seemed to be already using OOP in PHP 5.3. Might as well create a sorter class?

class Sorter{

    private $key;

    function __construct($key){
        $this->key = $key;
    }

    private function compare($a, $b){
        return strcmp($a[$this->key], $b[$this->key]);
    }

    public function sort($a){
        uasort($a, array($this, 'compare'));
    }

}


Another option is an anonymous function:

public function sortArray(&$array, $keyToCompare){
    return uasort($array, function($pairA, $pairB) uses ($keyToCompare) {
        return strcmp($pairA[$keyToCompare], $pairB[$keyToCompare]);
    });
}

Untested, on a train :D, but see the documentation for more info.

FYI, the pass by reference is unnecessary since you don't modify the array.. PHP won't make a copy so there is no memory issues passing by value.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号