PHP 变量类型与返回值类型声明php
标量类声明数组
默认状况下,全部的PHP文件都处于弱类型校验模式函数
PHP增长了标量类型声明的特征,标量类型声明有两种模:spa
强制模式code
严格模式blog
标量类型声明语法格式:string
declare(strict_types=1);it
代码中经过制定strict_types的值(1或者0),1表示严格类型效验模式,做用于函数调用和返回语句;0表示弱列席效验模式。io
可使用的类型参数有:function
int float bool string interfaces array callable
强制模式例如:
1 <?php 2 3 //强制模式 4 5 function sum(int ....$ints){ 6 7 return array_sum($ints); 8 9 } 10 11 print(sum(2,'3',4.1)); 12 13 ?>
程序输出结果为9;
例子将参数4.1转为整数4后再想加;
严格模式例如:
1 <?php 2 3 //严格模式 4 5 declare(strice_types=1); 6 7 function sum(int ....$ints){ 8 9 return array_sum$ints); 10 11 } 12 13 print(sum(2,'3',4.1); 14 15 ?>
程序采用了严格模式,因此参数中出现了不合适整数的类型就会报错,执行出结果为:
PHP Fatal error: Uncaught TypeError: Argument 2 passed to sum() must be of the type integer, string given, called in……
PHP 7 增长了对返回类型声明的支持,返回类型声明指明了函数返回值的类型。
能够声明的返回类型有:
int float bool string interfaces array callable
例如:
<?php declare(strict_types=1); function returnIntValue(int $value): int { return $value; } print(returnIntValue(5)); ?>
程序输出结果为5
<?php declare(strict_types=1); function returnIntValue(int $value): int { return $value + 1.0; } print(returnIntValue(5)); ?>
程序因为采用了严格模式,返回值必须是 int,可是计算结果是float,因此会报错,执行输出结果为:
Fatal error: Uncaught TypeError: Return value of returnIntValue() must be of the type integer, float returned...
PHP NULL 合并运算符
PHP 7 新增长的 NULL 合并运算符(??)是用于执行isset()检测的三元运算的快捷方式。
NULL 合并运算符会判断变量是否存在且值不为NULL,若是是,它就会返回自身的值,不然返回它的第二个操做数。
之前咱们这样写三元运算符:
1 <?php 2 // 获取 $_GET['site'] 的值,若是不存在返回 '运算符' 3 $site = $_GET['site'] ?? '运算符'; 4 5 print($site); 6 print(PHP_EOL); // PHP_EOL 为换行符 7 8 9 // 以上代码等价于 10 $site = isset($_GET['site']) ? $_GET['site'] : '运算符'; 11 12 print($site); 13 print(PHP_EOL); 14 15 $site = $_GET['site'] ?? $_POST['site'] ?? '运算符'; 16 17 print($site); 18 ?>
程序执行输出结果为
运算符
运算符
运算符
在PHP 7 中引入的其余返回值类型的基础上,一个新的返回值类型void被引入。 返回值声明为 void 类型的方法要么干脆省去 return 语句,要么使用一个空的 return 语句。 对于 void 函数来讲,null 不是一个合法的返回值。
<?php function swap(&$left, &$right) : void { if ($left === $right) { return; } $tmp = $left; $left = $right; $right = $tmp; } $a = 1; $b = 2; var_dump(swap($a, $b), $a, $b); ?>
程序运行结果为
null
int(2)
int(1)
list()支持在它内部去指定键名。这意味着它能够将任意类型的数组 都赋值给一些变量(与短数组语法相似)
<?php $data = [ ['id' => 1, 'name' => 'Tom'], ['id' => 2, 'name' => 'Fred'], ]; while (list('id' => $id, 'name' => $name) = $data) { // logic here with $id and $name } ?>