我一步一步跟随this video,但我似乎确实在某个地方犯了错误。任何人都可以解释我的错误在哪里以及如何解决它?
的index.php
<?php
require 'Classes/Calculator.php';
require 'Classes/OperatorInterface.php';
require 'Classes/Adder.php';
require 'Classes/Subtractor.php';
$c = new Calculator;
$c->setOperation(new Adder);
$c->calculate(10, 50);
echo $c->getResult();
?>
Calculator.php中
<?php
class Calculator{
protected $result;
protected $operation;
public function setOperation(OperatorInterface $operation){
$this->operation = $operation;
}
public function calculate(){
foreach(func_get_args() as $number){
$this->result = $this->operation->run($number, $this->$result);
}
}
public function getResult(){
return $this->result;
}
}
?>
Adder.php
<?php
class Adder implements OperatorInterface{
public function run($number, $result){
return $result + $number;
}
}
?>
OperatorInterface.php
<?php
interface OperatorInterface{
public function run($number, $result);
}
?>
我刚刚开始学习OOP,所以这可能是一个非常愚蠢的错误,提前抱歉...感谢您的帮助!
答案 0 :(得分:1)
Calculator::calculate()
中有一个拼写错误,$this->$result
应为$this->result
:
public function calculate(){
foreach(func_get_args() as $number){
$this->result = $this->operation->run($number, $this->result);
}
}
在引用班级的成员变量(属性)时,$
之后不需要->
。