Skip to content
Advertisement

PHP Class for adding two numbers

I am doing a challenge in PHP with OOP/classes and I am not sure why I am not passing the test case for two random numbers being added together. My syntax must be off somewhere, but I am very new to PHP so I am having trouble figuring it out. Here are the instructions for my challenge:

Write a class called Adder that sums two numbers. It should have a constructor that accepts two numbers, and a function getSum that returns the sum of those two numbers.

and this is what I see in the Output window: PHPUnit Testing

There was 1 failure:

  1. PhpCombinTest::test_sequence Sum 1 + 2 returned does not match the expected value 3 Failed asserting that 0 matches expected 3.

Any help is appreciated.

<?php
class Adder {
    public function __construct($num1, $num2) {
        $this->num1;
        $this->num2;
    }
    
    public function getSum() {
        return $this->num1 + $this->num2;
    }
    
    private $num1;
    private $num2;
} 
?>

Advertisement

Answer

You did not assign the parameters to the object properties in the constructor:

$this->num1 = $num1;
$this->num2 = $num2;
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement