I have created a class named calculator where I have set an arrow function as the property of the class. And I have passed that property to the init
method. Once I run this program, It is not generated output. My expected output is 15. The code is below.
<?php
namespace Calculate;
class calculator{
public $sum = fn(...$args) => array_sum($args);
public function init(){
return $this->sum(5, 10);
}
}
$cal = new calculator();
print $cal->init(); // Expected Output is 15
But on the other hand, when I am putting the sum
variable outside of the class and using it from the init method, It is working then. And it's providing the output 15. The code is below.
$sum = fn(...$args) => array_sum($args);
class calculator{
public function init(){
global $sum;
return $sum(5, 10);
}
}
$cal = new calculator();
print $cal->init(); // Output is 15
So, my question is can not I declare the arrow function as property or method of a class? If we can, what is the process, please?