Lex de Willigen Lex de Willigen - 2 months ago 11
PHP Question

Fatal error: Cannot access empty property in, why is it empty?

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!

Answer

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.