简单工厂模式中的问题,总是报错?
phpcn_u814
phpcn_u814 2017-02-16 11:23:21
0
2
911
<?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= OperFactory::createrOper('+');
// $obj->setNum(2, 2);
// var_dump($obj);
// echo $obj->getResult();

问题就在 $obj->setNum(2,2); 这里,但是怎么看流程,都好像没什么问题的

phpcn_u814
phpcn_u814

reply all(2)
数据分析师

Problems in simple factory model, errors always reported? -PHP Chinese website Q&A-Problems in simple factory mode, errors always reported? -PHP Chinese website Q&A

Let’s take a look and learn.

刘奇

$obj = OperFactory::createrOper('+');这个OperFactory的createOper方法没有返回值,应该return self::$obj = new OperAdd()

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template