1

我在扩展 ArrayObject 的 PHP 类中对项目进行排序时遇到问题。

我正在创建我的类,我想出添加 cmp() 函数的唯一方法是将它放在同一个文件中,但在类之外。由于 uasort 需要函数名作为字符串的方式,我似乎无法将其放在其他任何地方。

所以我这样做:

class Test extends ArrayObject{

    public function __construct(){
        $this[] = array( 'test' => 'b' );
        $this[] = array( 'test' => 'a' );
        $this[] = array( 'test' => 'd' );
        $this[] = array( 'test' => 'c' );
    }


    public function sort(){
        $this->uasort('cmp');
    }

}

function cmp($a, $b) {
    if ($a['test'] == $b['test']) {
        return 0;
    } else {
        return $a['test'] < $b['test'] ? -1 : 1;
    }
}

如果我只使用这样的一个类,这很好,但如果我使用两个(通过自动加载或要求),那么它会在尝试调用 cmp() 两次时中断。

我想我的意思是这样做似乎是一种不好的方法。有没有其他方法可以将cmp()函数保留在类本身中?

4

2 回答 2

4

您可以这样做,而不是调用函数,只需将其设为匿名函数。

仅限 PHP 5.3.0 或更高版本

class Test extends ArrayObject{

    public function __construct(){
        $this[] = array( 'test' => 'b' );
        $this[] = array( 'test' => 'a' );
        $this[] = array( 'test' => 'd' );
        $this[] = array( 'test' => 'c' );
    }


    public function sort(){
        $this->uasort(function($a, $b) {
            if ($a['test'] == $b['test']) {
                return 0;
            } else {
                return $a['test'] < $b['test'] ? -1 : 1;
            }
        });
    }
}

由于匿名函数仅适用于 PHP 5.3.0 或更高版本,因此如果您需要针对低于 5.3.0 的 PHP 版本,这将是更兼容的选项

PHP 5.3.0 以下

class Test extends ArrayObject{

    public function __construct(){
        $this[] = array( 'test' => 'b' );
        $this[] = array( 'test' => 'a' );
        $this[] = array( 'test' => 'd' );
        $this[] = array( 'test' => 'c' );
    }


    public function sort(){
        $this->uasort(array($this, 'cmp'));
    }

    public function cmp($a, $b) {
        if ($a['test'] == $b['test']) {
            return 0;
        } else {
            return $a['test'] < $b['test'] ? -1 : 1;
        }
    }

}
于 2015-05-29T16:24:49.193 回答
3

原来这在 PHP 文档(用户评论部分)中是正确的-> http://php.net/manual/en/function.uasort.php

magikMaker 4 年前 如果你想在类或对象中使用 uasort 的语法快速提醒:

<?php 

// procedural: 
uasort($collection, 'my_sort_function'); 

// Object Oriented 
uasort($collection, array($this, 'mySortMethod')); 

// Objet Oriented with static method 
uasort($collection, array('self', 'myStaticSortMethod')); 

?>
于 2015-05-29T16:22:34.343 回答