search
Homephp教程php手册PHP中的类型提示(type hinting)功能介绍,typehinting

PHP中的类型提示(type hinting)功能介绍,typehinting

概述

从PHP5开始,我们可以使用类型提示来指定定义函数时,函数接收的参数类型。如果在定义函数时,指定了参数的类型,那么当我们调用函数时,如果实参的类型与指定的类型不符,那么PHP会产生一个致命级别的错误(Catchable fatal error)。

类名称和数组

在定义函数时,PHP只支持两种类型声明:类名称和数组。类名称表名该参数接收的实参为对应类实例化的对象,数组表明接收的实参为数组类型。下面是一个例子:
复制代码 代码如下:
function demo(array $options){
  var_dump($options);
}

在定义demo()函数的时候,指定了函数接收的参数类型为数组。如果我们调用函数时,传入的参数不是数组类型,例如像下面这样的调用:
复制代码 代码如下:
$options='options';
demo($options);

那么将产生以下错误:
复制代码 代码如下:
Catchable fatal error: Argument 1 passed to demo() must be of the type array, string given,

可以使用null作为默认参数

注意

有一点需要特别注意的是,PHP只支持两种类型的类型声明,其他任何标量类型的声明都是不支持的,比如下下面的代码都将产生错误:
复制代码 代码如下:
function demo(string $str){
}
$str="hello";
demo($str)

当我们运行上面的代码时,string会被当做类名称对待,因此会报下面的错误:
Catchable fatal error: Argument 1 passed to demo() must be an instance of string, string given,

总结

类型声明也是PHP面向对象的一个进步吧,尤其是在捕获某种指定类型的异常时非常有用。
使用类型声明,也可以增加代码的可读性。
但是,由于PHP是弱类型的语言,使用类型声明又于PHP设计的初衷相悖。
到底使用还是不使用类型声明,大家见仁见智吧,本菜鸟不:).

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.