对于扩展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()函数保存在类本身中吗?
发布于 2015-05-29 16:24:49
您可以这样做,而不是调用一个函数,而是让它成为一个匿名函数。
仅限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;
}
});
}
}由于匿名函数只在PHP5.3.0或更高版本上工作,如果您需要将PHP版本定位在5.3.0以下,这将是更兼容的选项。
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-29 16:22:34
原来这在PHP文档(用户注释部分) -> http://php.net/manual/en/function.uasort.php中是正确的。
4年前,如果您想在类或对象中使用uasort,请快速提醒magikMaker:
<?php
// procedural:
uasort($collection, 'my_sort_function');
// Object Oriented
uasort($collection, array($this, 'mySortMethod'));
// Objet Oriented with static method
uasort($collection, array('self', 'myStaticSortMethod'));
?>https://stackoverflow.com/questions/30534363
复制相似问题