【发布时间】:2020-01-10 14:45:54
【问题描述】:
我有一个班级,我有一些用于计算的方法,例如除法(),乘法()等。
我想创建一个新方法,我们会调用它 showResult(),它会返回最后一个被调用的计算方法的结果。例如:
$foo = new MyTinyCalculator(30, 12);
echo $foo->add () . “\n”;
echo $foo->subtract () . “\n”;
echo $foo->multiply () . “\n”;
echo $foo->divide () . “\n”;
echo $foo->showResult () . “\n”;
/* displays
42
18
360
2.5
2.5
*/
到目前为止,这是我尝试过的:
class MyTinyCalculator
{
private $_a;
private $_b;
private $_result;
function __construct(int $a, int $b)
{
$this->_a = $a;
$this->_b = $b;
}
function getA()
{
return $this->_a;
}
function getB()
{
return $this->_b;
}
function setA($a)
{
$this->_a = $a;
}
function setB($b)
{
$this->_b = $b;
}
function getResult()
{
return $this->_result;
}
function setResult($result)
{
$this->_result = $result;
}
public function add()
{
return $this->_a + $this->_b . '<br>';
$this->_result = $this->_a + $this->_b;
}
public function substract()
{
return $this->_a - $this->_b . '<br>';
$this->_result = $this->_a - $this->_b;
}
public function divide()
{
return $this->_a / $this->_b . '<br>';
$this->_result = $this->_a / $this->_b;
}
public function multiply()
{
return $this->_a * $this->_b . '<br>';
$this->_result = $this->_a * $this->_b;
}
function showResult()
{
echo $this->_result;
}
}
$calculator = new MyTinyCalculator(30, 12);
echo $calculator->add();
echo $calculator->substract();
echo $calculator->multiply();
echo $calculator->divide();
echo $calculator->showResult();
它只显示:
42
18
360
2.5
【问题讨论】:
-
我建议从属性中删除前导
_,请参阅PSR-12 -
请不要通过破坏您的帖子为他人增加工作量。通过在 Stack Exchange 网络上发帖,您已在 CC BY-SA 4.0 license 下授予 Stack Exchange 分发该内容的不可撤销的权利(即无论您未来的选择如何)。根据 Stack Exchange 政策,帖子的非破坏版本是分发的版本。因此,任何破坏行为都将被撤销。如果您想了解更多关于删除帖子的信息,请参阅:How does deleting work?
标签: php class methods attributes