duancuan6466 2012-10-12 16:25
浏览 164

PHP:compareTo类似于Java

In an effort to utilize OOP in PHP, I was looking for a way to define functions within objects to use for sorting. in Java this is simple, as the compareTo() is automatically called by sorted arrays and such. I looked around PHP.net and couldn't find anything similar in PHP. I have resorted to what seems like a hack to me, so I'm wondering if anyone can lend some insight on an easier way.

CURRENT CODE:

class SomeObject {
    private $someField;

    function getSomeField() { return $this->someField; }

    function compareTo($other) {
        return $this->someField - $other->getSomeField();
    }
}

//in funcs.php
function objSort($a, $b) {
    return $a->compareTo($b);
}


//To sort an array
usort($array, objSort);

Is there an easier/more sleek way of doing this in PHP?

  • 写回答

2条回答 默认 最新

  • douleijiang8111 2012-10-12 16:31
    关注

    You could use anonymous function directly.

    class SomeObject {
        private $someField;
        function getSomeField() { return $this->someField; }
    }
    
    usort($array, function($a, $b) {
        return $a->getSomeField() - $b->getSomeField();
    });
    

    Or you could define a static function use to compare.

    class SomeObject {
        private $someField;
    
        function getSomeField() { return $this->someField; }
    
        static function compare($a, $b) {
            return $a->getSomeField() - $b->getSomeField();
        }
    }
    
    usort($array, array('SomeObject', 'compare'));
    
    评论

报告相同问题?

悬赏问题

  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备