Skip to content

Instantly share code, notes, and snippets.

@LinZap
Created February 17, 2016 13:39
Show Gist options
  • Save LinZap/f13d1b72e09c7b530770 to your computer and use it in GitHub Desktop.
Save LinZap/f13d1b72e09c7b530770 to your computer and use it in GitHub Desktop.
display Progress (PHP ver.)
<?php
class Progress{
private $max;
private $value;
private $length = 10;
private $style = "=";
/*
@arg1 進度條初始值
@arg2 進度條最大值
*/
function __construct($val=0,$max=100){
$this->value = $val;
$this->max = $max;
}
/*
@arg1 設定進度條最大方塊數
#
*/
public function setStyle($len=10,$style="="){
$this->length = $len;
$this->style = $style;
}
/*
更新進度條,並畫在介面
*/
public function upgrade($val){
$this->value = $val;
$this->render();
}
/*
結束進度條
*/
public function done(){
echo "\n";
}
/*
畫出進度條
*/
private function render(){
if($this->value>$this->max) $this->value = $this->max;
$persent = $this->getPersent();
$fill_num = $this->getLength();
$space_num = $this->length - $fill_num;
$pgs = "|";
for ($i=0; $i < $fill_num ; $i++) $pgs .= $this->style;
for ($i=0; $i < $space_num; $i++) $pgs .= " ";
$pgs .= "| ".$persent."% \r";
echo $pgs;
}
/*
換算應該要畫幾個格子
*/
private function getLength(){
return floor($this->value/($this->max/$this->length));
}
/*
換算多少 %
*/
private function getPersent(){
return round(($this->value*100)/$this->max);
}
}
?>
@LinZap
Copy link
Author

LinZap commented Feb 17, 2016

使用方式

引入

include_once 'Progress.php';

Basic

$pgs = new Progress(0,100);

for ($i=0; $i <= 100 ; $i+=10) { 
    $pgs->upgrade($i);
    sleep(1);
}

$pgs->done();

自訂長度,樣式

$pgs = new Progress(0,100); //(初始值,最大值)
$pgs->setStyle(20,""); //(進度條長度,使用樣式)

// 使用進度條樣式時,要注意編碼問題

Demo

progress

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment