PHP function parameter casting function allows parameters to be converted to specific data types to ensure correct data input. Casting syntax: function func(mixed $param): type {...}, where mixed means that any type of data can be accepted, and type means the expected type. PHP supports coercion of parameters into int, float, string, bool and array types. Coercion will not modify the original parameter value. Casting is useful when strict type checking is required.
Forced type conversion PHP function parameter
Introduction
In PHP function Parameters can be cast to specific data types. This is useful when ensuring that a function receives the required type of data.
Syntax
function func(mixed $param): type { // 函数体 }
Among them, mixed
indicates that the parameter can be any type of data, and type
indicates that the function expects to receive data type.
Practical case
Suppose we have a function get_number()
, which should receive a numeric parameter and divide it by 2. We can force a parameter to be converted to an integer type using the following syntax:
function get_number(int $num): float { return $num / 2; }
Code Example
// 正确调用 $result = get_number(20); // 10 // 错误调用 $result = get_number("10"); // Fatal Error: Argument 1 passed to get_number() must be of the type integer, string given
Other Conversion Types
In addition to int
, PHP also supports the following cast types:
float
: floating point number string
: Stringbool
: Boolean valuearray
: ArrayNotes
The above is the detailed content of Casting of PHP function parameters. For more information, please follow other related articles on the PHP Chinese website!