Casting of PHP function parameters

王林
Release: 2024-04-19 14:51:02
Original
988 people have browsed it

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 {
    // 函数体
}
Copy after login

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;
}
Copy after login

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
Copy after login

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!

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!