I made a second class that inherits everything from the first. It should display the result of the sum () method in the square, but this does not happen, because initially the result property has a value of 0 , I need to assign this property the value of $ firstNumber but I don’t know how?

<?php header('Content-Type: text/html; charset:utf-8'); error_reporting(-1); class CalkSum{ public function __construct($firstNumber){ $this->firstNumber = $firstNumber; } public $result = 0; public function sum(){ for($i = 0; $i < func_num_args(); $i++){ $this->result = $this->result+ func_get_args()[$i]; } return $this->result + $this->firstNumber; } } class SumSquare extends CalkSum{ public function square(){ return $this->result * $this->result; } } $ob2 = new SumSquare(100); $res1 = $ob2->sum(1,2,3); echo 'Результат сложения ' . $ob2->firstNumber . ' + аргументы = ' . $res1; echo '<br>'; echo $res1 . ' в квадрате = ' . $ob2->square(); 

106 * 106 should output 11236, and it outputs 36 from me

    3 answers 3

     class CalkSum{ public $result = 0; public function __construct($firstNumber){ $this->firstNumber = $firstNumber; $this->result = $firstNumber; } public function sum(){ for($i = 0; $i < func_num_args(); $i++){ $this->result = $this->result+ func_get_args()[$i]; } return $this->result; } } class SumSquare extends CalkSum{ public function square(){ return $this->result * $this->result; } } $ob2 = new SumSquare(100); var_dump($ob2); $res1 = $ob2->sum(1,2,3); echo 'Результат сложения ' . $ob2->firstNumber . ' + аргументы = ' . $res1; echo '<br>'; echo $res1 . ' в квадрате = ' . $ob2->square(); 

      You simply return the result of the sum method, so you have $result = 6 , you must first update the variable and then return it, like this:

       public function sum(){ for($i = 0; $i < func_num_args(); $i++){ $this->result = $this->result+ func_get_args()[$i]; } $this->result += $this->firstNumber return $this->result; } 
      • now generally firstNumber doesn't add up - DivMan
      • I announced it in __construct - DivMan

      Declare a class property. Otherwise, where to put the value?

       class CalkSum{ public $firstNumber; ... 
      • I announced it in __construct - DivMan
      • In the constructor, you do not declare a value. The declaration of properties (class variables) occurs usually in the first lines of the class description. - Kirill Korushkin
      • You won't believe it, but magically the $ firstNumber property will be created despite the fact that it is not declared ideone.com/ki0Q0n - Alexey Shimansky