在php中有哪些标量类型,PHP7功能之标量类型声明

PHP7引入了Scalar类型声明,增强了函数方法的类型检查,提高了执行效率。强制模式是默认模式,而严格模式需通过`declare(strict_types=1);`开启。在严格模式下,函数参数类型不匹配将引发致命错误,而非警告。此特性改进了代码的健壮性,确保类型一致性。
摘要由CSDN通过智能技术生成

在 PHP7 中为了提高执行效率,引入了一个新的功能,即在函数方法中增加了 Scalar 类型声明(标量类型声明),这样做节省了对数据类型的检测。标量类型声明有如下的两个选项:强制模式:强制是默认的模式,不需要指定。

严格模式:严格的模式必须明确暗示。RFC 给每一个 PHP 文件,添加一句新的可选指令(declare(strict_type=1);),让同一个 PHP 文件内的全部函数调用和语句返回,都有一个“严格约束”的标量类型声明检查。

可以使用上述模式强制执行以下类型的函数参数:

int

float

bool

string

interfaces

array

callable

强制模式-示例<?php

// Coercive mode

function sum(int ...$ints) {

return array_sum($ints);

}

print(sum(2, '3', 4.1));

?>

运行上述代码,它产生以下浏览器输出:9

严格模式-示例<?php

// Strict mode

declare(strict_types=1);

function sum(int ...$ints) {

return array_sum($ints);

}

print(sum(2, '3', 4.1));

?>

运行上述代码,它产生以下浏览器输出:PHP Fatal error: Uncaught TypeError: Argument 2 passed to sum() must be of the type integer, string given, called in /soft/node/run.php on line 7 and defined in /soft/node/run.php:4 Stack trace: #0 /soft/node/run.php(7): sum(2, '3', 4.1) #1 {main} Next TypeError: Argument 3 passed to sum() must be of the type integer, float given, called in /soft/node/run.php on line 7 and defined in /soft/node/run.php:4 Stack trace: #0 /soft/node/run.php(7): sum(2, '3', 4.1) #1 {main} thrown in /soft/node/run.php on line 4

严格模式的校验行为:严格的类型校验调用拓展或者 PHP 内置函数,会改变 zend_parse_parameters 的行为。特别注意,失败的时候,它会产生E_RECOVERABLE_ERROR 而不是E_WARNING。严格类型校验规则是非常直接的:只有当类型和指定类型声明匹配,它才会接受,否则拒绝。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值