Home >Backend Development >PHP Tutorial >Casting of PHP function parameters

Casting of PHP function parameters

王林
王林Original
2024-04-19 14:51:021317browse

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.

PHP 函数参数的强制类型转换

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 : String
  • bool: Boolean value
  • array: Array

Notes

  • Casting does not change the value of the original parameter.
  • If the parameter cannot be converted to the specified type, an error or warning will be thrown.
  • Casting is very useful in environments where strict type checking is required.

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!

Statement:
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

Related articles

See more