首页 > 技术文章 > 策略模式

sunlong88 2018-04-02 11:13 原文

<?php
<?php
interface math{
    public function calc($op1,$op2);
}

class mathadd implements math{
    public function calc($op1,$op2){
        return $op1+$op2;
    }
}
class mathsub implements math{
    public function calc($op1,$op2){
        return $op1-$op2;
    }
}
class mathmul implements math{
    public function calc($op1,$op2){
        return $op1*$op2;
    }
}
class mathdiv implements math{
    public function calc($op1,$op2){
        return $op1/$op2;
    }
}

class cmath{
    protected $calc = null;
    public function __construct($type){
        $calc = "math".$type;
        $this->calc = new $calc();
    }
    public function calc($op1,$op2){
        return $this->calc->calc($op1,$op2);
    }
}

$type = $_POST['op'];
$cmath = new cmath($type);
echo $cmath->calc($op1, $op2);

  

推荐阅读