Home  >  Q&A  >  body text

简单工厂的异常,不知如何修改

<?php
//接口
interface calc{
    public function getResult();
}
//运算类
class Operation{
    protected $num1=0;
    protected $num2=0;
    protected $result=0;
    
    public function setNum($num1,$num2){
        $this->num1 = $num1;
        $this->num2 = $num2;
    }
}

//四则运算类
class OperAdd extends Operation implements calc{
    public function getResult(){
        return $this->result=$this->num1+$this->num2;
    }
}
class OperSub extends Operation implements calc{
    public function getResult(){
        return $this->result=$this->num1-$this->num2;
    }    
}
class OperMul extends Operation implements calc{
    public function getResult(){
        return $this->result=$this->num1*$this->num2;
    }
}
class OperDiv extends Operation implements calc{
    public function getResult(){
        if(intval($this->num2)==0){
            return $this->result="被除数不能为‘0’!";
        }else{
            return $this->result=$this->num1/$this->num2;     
        }        
    }
}
class OperFactory{
    private static $obj;
    public static function createrOper($type){
        try {
            switch ($type){
                case'+';
                    self::$obj = new OperAdd();
                    break;
                case'-';
                    self::$obj = new OperSub();
                    break;
                case'*';
                    self::$obj = new OperMul();
                    break;
                case '/':
                    self::$obj = new OperDiv();
                    break;    
                    default:
                        throw new Exception('unknow type');
                }
            } catch (Exception $e) {
                echo $e->getMessage();
        }
    }
}
$obj = OperFactory::createrOper('+');
$obj->setNum(2,2);
echo $obj->getResult();



问题在  $obj->setNum(2,2);总是找不到对象,实在是找不出来问题,求解。

phpcn_u737phpcn_u7372710 days ago709

reply all(2)I'll reply

  • 数据分析师

    数据分析师2017-10-01 00:19:36

    Exception in a simple factory, I don’t know how to modify it-PHP Chinese website Q&A-Exception in a simple factory, I don’t know how to modify it-PHP Chinese website Q&A

    Look around and learn.

    reply
    0
  • phpcn_u737

    phpcn_u7372017-02-14 16:09:31

    好了···我发现了问题  原来是没有返回值  搞定了

    reply
    1
  • Cancelreply