How i can use arrow or anonymous function like this in php or something similar syntax to achieve this.
class calculator{
// $sum = fn(...$args) => array_sum($args);
public function hello(){
// $sum(5, 10)
}
}
or this way
$sum = fn(...$args) => array_sum($args);
class calculator{
public function hello(){
// $sum(5, 10)
}
}
An arrow function in PHP is not a special kind of function, just a convenient syntax for declaring an "anonymous function" or "closure" - that is, a function which you can pass around as a normal variable.
So once you create your anonymous function $sum, it is just like any other variable - you have to pass that variable to where you need it. Normally, this is done so that you can change which function gets called by passing different functions in - think of something like registering an error handler, for instance.
Your first example is not legal PHP, because you can't declare a variable floating around in a class like that. Your second example is valid syntax, but the variable $sum has not been passed into the function, so doesn't exist there. A working (but not very useful) example would be this:
$sum = fn(...$args) => array_sum($args);
class calculator{
public function hello(callable $functionToCall){
echo $functionToCall(5, 10);
}
}
$calc = new calculator();
$calc->hello($sum);
If all you're looking for is to add a sum method to the class, you don't need arrow syntax at all:
class calculator{
public function sum(...$args) {
return array_sum($args);
}
}
Similarly, if all you want is a function named sum available everywhere, just declare it as a normal function, not a closure:
function sum(...$args) {
return array_sum($args);
}
class calculator {
public function hello() {
echo sum(5, 10);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With