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'));
    
    评论

报告相同问题?

悬赏问题

  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序