PHP 8 introduced type inference, allowing the return type to be specified in the function declaration (such as functionName(): type). For example, a function named sum returns type int and can be called with $name = $user->getName(). It should be noted that the actual return type must be consistent with the declared return type, otherwise a TypeError exception will be raised.
Type inference of PHP function return values
In PHP 8, the type inference feature was introduced to help you infer functions The type of return value. This is done by specifying the expected return type in the function declaration. The syntax is as follows:
function functionName(): type { // 函数体 }
For example, we define a function named sum
that adds two numbers and returns an integer value:
function sum(int $a, int $b): int { return $a + $b; }
Practical Case
Suppose we have a User
class, which has a getName
method, which returns a string:
class User { public function getName(): string { return "John Doe"; } }
The following is how to use type inference to call the getName
method:
$user = new User(); $name = $user->getName(); // $name 将被推断为字符串类型
Notes
int|string
), the function can return any type that conforms to the union type. @return
tag to specify the type of the function's return value, but it will be overridden by the type inference feature. The above is the detailed content of How to infer the type of PHP function return value?. For more information, please follow other related articles on the PHP Chinese website!