0

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?

knittl
  • 246,190
  • 53
  • 318
  • 364
  • 6
    This causes an error: https://3v4l.org/L1MZo . A property's initial value is effectively a constant. And it would try to set that _before_ the init() function is called, so there'd be no value set for it to work with. It's not really clear what advantage you're trying to get from doing it this way. This should just be implemented as a function of the class, rather than a property - https://3v4l.org/pjhRa. – ADyson Jul 04 '23 at 12:17

1 Answers1

2

First, the arrow function should be assigned to a variable, not a class property. Arrow functions in PHP cannot be directly assigned as class properties. Instead, you can define a regular method that uses the arrow function internally. Here's an updated version of the code:

namespace Calculate;

class Calculator {
    private $sum;

    public function __construct() {
        $this->sum = fn(...$args) => array_sum($args);
    }

    public function init() {
        return ($this->sum)(5, 10);
    }
}

$cal = new Calculator();
echo $cal->init(); // Output: 15


Now, when you run the code, it will correctly output 15, which is the expected result.