PHP Abstract Class

PHP Abstract Classes What is the output of the following code? abstract class Calc { abstract public function calculate($param); protected function getConst() { return 4; } } class FixedCalc extends Calc { public function calculate($param) { return $this->getConst() + $param; } } $obj = new FixedCalc(); echo $obj->calculate(38);

12th Nov 2021, 11:24 AM
Ayatullah Adi Sasono
Ayatullah Adi Sasono - avatar
1 Answer
Abstract classes are not instantiable, they were meant to be extended by other classes which were supposed to provide the implementation of the abstract class' functions. So here, `FixedCalc` extends abstract class `Calc`, and provides an implementation of the `calculate()` function. The implementation of `calculate()` function inside `FixedCalc` class defines that the function returns whatever value returned by the protected method `getConst()` plus the value of argument <$param>. Basically, the implementation of `calculate()` function returns the value returned by `getConst()` (value 4) plus the value of argument <$param> (value 38). And in the end of the snippet, you output that value into the document's body. Hth, cmiiw
12th Nov 2021, 2:07 PM