如何创建一个类计算器,它可以执行不同的运算,如加法、乘法,但格式为$test->two()->add()->one()
→结果是3?
class Test
{
private $result;
function __construct()
{
$this->result = 0;
}
function one()
{
$this->result = 1;
return $this;
}
function two()
{
$this->result = 2;
return $this;
}
function add()
{
$this->result += $this->result;
return $this;
}
function getResult()
{
return $this->result;
}
}
$test = new Test();
$a = $test->One()->add()->two();
var_dump($a->getResult());
我写了这个程序,结果不正确。
结果返回2,但必须是3(1+2(。
这里有一个解决方案。
它是在add()
或subtract()
不直接执行任何工作的基础上工作的;挂起";操作,而one()
或two()
(为了简单起见,我将该样式快捷为key($num)
,我认为它更好、更灵活(实际上使用输入中指定的数字执行add()
或subtract()
指定的最后一个操作。
它的工作原理是使用PHP的功能来指定要使用字符串值调用的函数。有点生气,但似乎有效。
class Calculator
{
private $result;
private $nextOp;
function __construct()
{
$this->result = 0;
$this->nextOp = "addVal";
}
function key($num)
{
$this->{$this->nextOp}($num);
return $this;
}
function add()
{
$this->nextOp = "addVal";
return $this;
}
function subtract()
{
$this->nextOp = "subtractVal";
return $this;
}
private function addVal($num)
{
$this->result += $num;
}
private function subtractVal($num)
{
$this->result -= $num;
}
function result()
{
return $this->result;
}
}
$test = new Calculator();
$a = $test->key(1)->add()->key(2)->key(3)->subtract()->key(2)->result();
var_dump($a);
从而输出CCD_ 9。
注意:它假设,如果您编写例如key(1)->add()->key(2)->key(2)
,对key(2)
的第二次调用也会执行add
,因为这是指定的最后一个操作(因此在这种情况下,结果将是5
(,而且初始操作也总是add
(尽管我猜您可以允许在构造函数中指定(。我不知道这些假设在您的场景中是否可以接受,您没有指定如果用户写这样的东西应该发生什么,或者类应该对初始值做什么。
现场演示:http://sandbox.onlinephpfunctions.com/code/0be629f803261c35017ae49a51fa24385978568d
这是我的回应。运行得很好
// Interface des opérations
interface Operation {
public function plus();
public function minus();
public function divededInto();
public function times();
public function doOperation($value);
}
// Class Calculator
class Calculator implements Operation {
private $result;
private $operation;
private $numbers;
public function __construct($numbers) {
$this->numbers = $numbers;
$this->result = 0;
$this->operation = null;
}
//Surcharge de la méthode __call
public function __call($name, $arguments){
$name = strtolower($name);
$this->doOPeration($this->numbers[$name]);
$this->operation = null;
return $this;
}
// Exécution de l’opération
public function doOperation($value){
switch ($this->operation ){
case '+':
$this->result += $value;
break;
case '-':
$this->result -= $value;
break;
case '/':
$this->result = intDiv($this->result,$value);
break;
case '*':
$this->result *= $value;
break;
default : $this->result = $value;
}
}