Parameters and return values ​​of PHP functions

WBOY
Release: 2024-04-13 17:12:01
Original
1106 people have browsed it

PHP function parameters can have type specifications and default values, and the return value can return a type specification value. For example, a function sum() that calculates the sum of two numbers and returns an integer takes two integer arguments, one of which has the default value "Guest".

PHP 函数的参数和返回值

Parameters and return values ​​of PHP functions

Function parameters

Function parameters is the data value passed to the function. They allow functions to perform specific tasks. Parameters appear as a comma-separated list in function definitions and function calls.

function function_name(parameter1, parameter2) {}

Parameter type description

Parameters can have type specifications. The type specification specifies the expected data type of the parameter.

function sumOfNumbers(int $num1, int $num2) {}
Copy after login

In this example, the sumOfNumbers() function expects two integer parameters ($num1 and $num2).

Default parameter values

Parameters can have default values. When a function is called, if a parameter value is specified, it is used. If not specified, the default value is used.

function greetUser($name = "Guest") {}
Copy after login

In this example, the greetUser() function has a default parameter $name with the value "Guest".

Return value

The function can return a value. The return value is the data value of the function execution result. The return value is specified using the return statement.

function function_name(): return_type {}

Return value type specification

The return value can have a type specification. The type specification specifies the expected data type of the return value.

function getSumOfNumbers(): int {}
Copy after login

In this example, the getSumOfNumbers() function returns an integer.

Practical Case

Consider a function that calculates the sum of two numbers:

function sum(int $num1, int $num2): int {
  return $num1 + $num2;
}

// 调用函数
$result = sum(5, 10);

// 打印结果
echo $result; // 输出 15
Copy after login

The above is the detailed content of Parameters and 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!