Home > Backend Development > PHP Tutorial > How to infer the type of PHP function return value?

How to infer the type of PHP function return value?

WBOY
Release: 2024-04-10 21:24:01
Original
1055 people have browsed it

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.

PHP 函数返回值的类型如何推断?

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 {
  // 函数体
}
Copy after login

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;
}
Copy after login

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";
  }
}
Copy after login

The following is how to use type inference to call the getName method:

$user = new User();
$name = $user->getName(); // $name 将被推断为字符串类型
Copy after login

Notes

  • If the actual return type is different from the declared return type Without a match, PHP will raise a TypeError exception.
  • For inherited classes, the return type of the derived class can override the return type of the base class.
  • For union types (such as int|string), the function can return any type that conforms to the union type.
  • You can still use the @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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template