php总是报错,php - 简单工厂模式中的问题,总是报错
php - 簡單工廠模式中的問題,總是報錯
PHPzhong2017-04-11 09:53:49 0 3 101
//接口
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 Operp 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 Operp();
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); 這里,但是怎么看流程,都好像沒什么問題的
回答
3
0
分享
全部回復 (3)
大家講道理2017-04-11 09:55:493樓
$obj = OperFactory::createrOper('+');這個OperFactory的createOper方法沒有返回值,應該return self::$obj = new OperAdd()
回復
迷茫2017-04-11 09:55:492樓
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 Operp();
break;
default:
throw new Exception('unknow type');
}
} catch (Exception $e) {
echo $e->getMessage();
}
return self::$obj;
}
回復
巴扎黑2017-04-11 09:55:491樓
建議去翻譯下設計模式的資料設計模式,希望對你有幫助
回復
總結
以上是生活随笔為你收集整理的php总是报错,php - 简单工厂模式中的问题,总是报错的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: 想让降价别想!NV继续促销3060等RT
- 下一篇: JAVA子类和父类在同一个包中,子类和父
