doufubu2518 2016-09-30 22:00
浏览 22
已采纳

致命错误:无法访问空属性,为什么它是空的? [关闭]

I follow this video step by step, but I do seem to have a mistake somewhere. Can anyone explain where my mistake is and how to fix it?

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);
}
?>

I just started learning OOP, so it might be a really stupid mistake, sorry in advance... Thanks for the help!

  • 写回答

1条回答 默认 最新

  • dt3999 2016-09-30 22:19
    关注

    There is a typo in Calculator::calculate(), $this->$result should be $this->result:

    public function calculate(){
        foreach(func_get_args() as $number){
            $this->result = $this->operation->run($number, $this->result);
        }
    }
    

    You don't need the $ after the -> when referring to a member variable (property) of the class.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64