Home > Backend Development > PHP Tutorial > What are the restrictions on the return values ​​of PHP functions?

What are the restrictions on the return values ​​of PHP functions?

王林
Release: 2024-04-16 12:15:01
Original
709 people have browsed it

The return value of a PHP function can be a scalar, composite, or resource type, but it can only return one value. The return value of a scalar type is coerced to a scalar type. A void function cannot return any value. Functions that do not declare a return value type are assumed to return void.

PHP 函数的返回值有什么限制?

Restrictions on the return value of the PHP function

The return value of the PHP function can be any data type, including:

  • Scalar Type (such as int, float, string, bool, null)
  • Composite type (such as array, object)
  • Resource type (such as file pointer, database link)

However, there are some restrictions on the return value type:

  • A function can only return one value.
  • The return value of a scalar type is coerced to a scalar type, even if the function returns a composite type (such as an array or object).
  • If a function is declared to return void, it cannot return any value.

Practical case:

The following function is declared to return an integer:

function sum($a, $b): int
{
    return $a + $b;
}
Copy after login

This function receives two parameters and returns their sum. If you try to return a string or array, the compiler will report an error:

// 编译器错误
function sum($a, $b): string
{
    return $a + $b;
}
Copy after login

Note:

  • If the function is declared to return void, even if you use ## The #return statement should also not return any value. Doing so may result in unpredictable behavior.
  • If the function does not declare any return value type, PHP will assume that it returns void.

The above is the detailed content of What are the restrictions on the return values ​​of PHP functions?. 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