The issue is raised when an arrow function has an invalid parameter and/or return type hint. This can result in type errors at the runtime.
This issue will be raised in any of the following cases:
namespace App\Services;
class Addition {}
class Division {}
namespace App\Controllers;
use App\Services\Subtract;
class CalcController
{
public function getSubtract(): void
{
// "Subtract" doesn't exist in the App\Services namespace, leading to an error
fn(): Subtract => new Subtract();
}
}
// union type syntax will cause an error in PHP versions below 8.0
$sum = fn(int|float $x, int|float $y): int|float => $x + $y;
$sum(2, 2.5);
// invalid: required parameter $z follows optional parameter $y, this is deprecated in PHP 8.0 and above.
$sum = fn(int $x, int $y = 0, int $z): int => $x + $y + $z;
$sum(2, 4, 6);
namespace App\Services;
class Addition {}
class Subtract {}
class Division {}
namespace App\Controllers;
use App\Services\Subtract;
class CalcController
{
public function getSubtract(): void
{
// Make sure the return type is defined in a namespace that you have used in this file.
fn(): Subtract => new Subtract();
}
}
// Use the `mixed` keyword if a function can accept or return multiple types:
$sum = fn(mixed $x, mixed $y): mixed => $x + $y;
// You can also use PHPDoc blocks to typehint parameters and return types:
/**
* @var $x int|float
* @var $y int|float
*
* @return int|float
*/
$sum = fn(mixed $x, mixed $y): mixed => $x + $y;
$sum(2, 2.5);
/**
* Default values must either not be specified,
* or you must ensure that any parameters with default values appear after required parameters.
*/
$sum = fn(int $x, int $y, int $z): int => $x + $y + $z;
$sum(2, 4, 6);