PHP 语言实现的超级简化且简单版的 x.y.z 语义版本号比较

yufei       3 年, 8 月 前       727

PHP 语言版的超级简化版和简单版的 x.y.z 语义话版本号比较,话不多说,直接上代码了

<?php 

class Semver {
    public $majer = 0;
    public $minor = 0;
    public $patch = 0;
    public $extra = null;

    public function __construct($majer = 0,$minor = 0,$patch = 0,$extra = null) {
        $this->majer = $majer;
        $this->minor = $minor;
        $this->patch = $patch;
        $this->extra = $extra;
    }

    public static function parse($ver) {
        $t = explode('.',$ver);
        $majer = isset($t[0]) ? intval($t[0]) : 0;
        $minor = isset($t[1]) ? intval($t[1]) : 0;
        $patch = isset($t[2]) ? intval($t[2]) : 0;
        return new Semver($majer,$minor,$patch,null);
    }

    public function cmp(Semver $that) {

        if ($this->majer != $that->majer)
        {
            return $this->majer > $that->majer ? 100 : -1;
        }

        if ($this->minor != $that->minor)
        {
            return $this->minor > $that->minor ? 10 : -1;
        }

        if ($this->patch != $that->patch) {
            return $this->patch > $that->patch ? 1 : -1;
        }

        return 0;
    }

    public static function latest($thats)
    {
        $latest = $thats[0];
        foreach($thats as $that) {
            if ($latest->cmp($that) < 0) {
                $latest = $that;
            }
        }

        return $latest;
    }

    public function __toString() {
        return $this->majer . '.' . $this->minor . '.' . $this->patch;
    }
}


$ar = [
    new Semver(1,2,3),
    new Semver(1,2,5),
    new Semver(1,2,1),
    new Semver(1,0,0),
    new Semver(1,2,2),
];

echo Semver::latest($ar),"\n";
目前尚无回复
简单教程 = 简单教程,简单编程
简单教程 是一个关于技术和学习的地方
现在注册
已注册用户请 登入
关于   |   FAQ   |   我们的愿景   |   广告投放   |  博客

  简单教程,简单编程 - IT 入门首选站

Copyright © 2013-2022 简单教程 twle.cn All Rights Reserved.