Home > Article > Backend Development > Unpacking the elements of a PHP function
PHP function syntax: Function name: starts with a letter or underscore, contains only letters, numbers, and underscores, and is case-sensitive. Parameters: Can accept one or more variables, type is scalar or complex type. Return value: Return using the return statement, or NULL if there is no return.
The syntax of the PHP function follows the following format:
function function_name(parameter1, parameter2, ...) { // 函数的主体 }
The function name is a collection of identifiers. It must start with a letter or underscore, and can only contain letters, numbers, and underscores. Function names are case-sensitive.
The function can accept one or more parameters. Parameters are variables available within the function body. Parameter types can be scalars (such as integers, strings, etc.) or complex types (such as arrays, objects, etc.).
A function can return a value or no value. Use the return
statement to return a value. Without the return
statement, the function returns NULL
.
<?php // 定义计算三角形面积的函数 function triangle_area(float $base, float $height): float { // 计算面积 $area = 0.5 * $base * $height; // 返回面积 return $area; } // 输入底边和高度 $base = 10; $height = 5; // 计算并打印三角形面积 $area = triangle_area($base, $height); echo "三角形的面积为:$area 平方单位"; ?>
In this example, the triangle_area
function accepts two parameters: base and height. It calculates and returns the area of a triangle.
The above is the detailed content of Unpacking the elements of a PHP function. For more information, please follow other related articles on the PHP Chinese website!