<?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); 这里,但是怎么看流程,都好像没什么问题的
シンプルファクトリーモードで問題が発生し、エラーが常に報告されますか? -PHP 中国語 Web サイト Q&A - シンプル ファクトリ モードで問題が発生し、常にエラーが報告されますか? -PHP中国語サイトQ&A
ぜひ見て学んでください。
$obj = OperFactory::createrOper('+');这个OperFactory的createOper方法没有返回值,应该return self::$obj = new OperAdd()