- 支持goto语句
goto a;
echo 'Foo';
a:
echo 'Bar';
for($i=0,$j=50; $i<100; $i++) {
while($j--) {
if($j==17) goto end;
}
}
echo "i = $i";
end:
echo 'j hit 17';
- 三元运算符增加了一个快捷书写方式
原本格式为是(expr1) ? (expr2) : (expr3)
如果expr1结果为True,则返回expr2的结果。
新增一种书写方式,可以省略中间部分,书写为expr1 ?: expr3
如果expr1结果为True,则返回expr1的结果
$expr1=1;
$expr2=2;
//原格式
$expr=$expr1?$expr1:$expr2
//新格式
$expr=$expr1?:$expr2
输出结果: 1 1
- 空合并运算符(??)
简化判断
$param = $_GET['param'] ?? 1;
相当于:
$param = isset($_GET['param']) ? $_GET['param'] : 1;
- 太空船操作符(组合比较符)
太空船操作符用于比较两个表达式。当 a大于、等于或小于b 时它分别返回 -1 、 0 或 1 。 比较的原则是沿用 PHP 的常规比较规则进行的。
// Integers
echo 1 <=> 1; // 0
echo 1 <=> 2; // -1
echo 2 <=> 1; // 1
// Floats
echo 1.5 <=> 1.5; // 0
echo 1.5 <=> 2.5; // -1
echo 2.5 <=> 1.5; // 1
// Strings
echo "a" <=> "a"; // 0
echo "a" <=> "b"; // -1
echo "b" <=> "a"; // 1
- 常量增强
允许常量计算,允许使用包含数字、字符串字面值和常量的标量表达式
const A = 2;
const B = A + 1;
class C
{
const STR = "hello";
const STR2 = self::STR + ", world";
}
允许常量作为函数参数默认
function test($arg = C::STR2)
类常量可见性 现在起支持设置类常量的可见性。
class ConstDemo
{
const PUBLIC_CONST_A = 1;
public const PUBLIC_CONST_B = 2;
protected const PROTECTED_CONST = 3;
private const PRIVATE_CONST = 4;
}
通过define()、const 定义常量数组
const TYPE = [1, 2, 3];
define('ANIMALS', ['dog', 'cat', 'bird']);
echo ANIMALS[1]; // outputs "cat"
- 可变函数参数
function add(...$args)
{
$result = 0;
foreach($args as $arg)
$result += $arg;
return $result;
}
- 返回值类型声明
function show(): array
{
return [1,2,3,4];
}
function arraysSum(array ...$arrays): array
{
return array_map(function(array $array): int {
return array_sum($array);
}, $arrays);
}
- 参数解包功能
在调用函数的时候,通过 … 操作符可以把数组或者可遍历对象解包到参数列表,这和Ruby等语言中的扩张(splat)操作符类似
function add($a, $b, $c) {
return $a + $b + $c;
}
$arr = [2, 3];
add(1, ...$arr);
- Getter 和 Setter
class TimePeriod {
public $seconds;
public $hours {
get { return $this->seconds / 3600; }
set { $this->seconds = $value * 3600; }
}
}
$timePeriod = new TimePeriod;
$timePeriod->hours = 10;
var_dump($timePeriod->seconds); // int(36000)
var_dump($timePeriod->hours); // int(10)
10.迭代器
目前,自定义迭代器很少使用,因为它们的实现,需要大量的样板代码。生成器解决这个问题,并提供了一种简单的样板代码来创建迭代器
例如,你可以定义一个范围函数作为迭代器:
function *xrange($start, $end, $step = 1) {
for ($i = $start; $i < $end; $i += $step) {
yield $i;
}
}
foreach (xrange(10, 20) as $i) {
// ...
}
- finally关键字
这个和java中的finally一样,经典的try … catch … finally 三段式异常处理。
- 多异常捕获处理
一个catch语句块现在可以通过管道字符(|)来实现多个异常的捕获。 这对于需要同时处理来自不同类的不同异常时很有用。不同的抛出对应下面相应的捕获
try {
// some code
} catch (FirstException | SecondException $e) {
// handle first and second exceptions
} catch (\Exception $e) {
// ...
} finally{
//
}
- Upload progress 文件上传
Session提供了上传进度支持,通过 $_SESSION[“upload_progress_name”] 就可以获得当前文件上传的进度信息,结合Ajax就能很容易实现上传进度条了。
- HTTP状态码在200-399范围内均被认为访问成功
15.一个简单的密码散列API
$password = "foo";
// creating the hash
$hash = password_hash($password, PASSWORD_BCRYPT);
// verifying a password
if (password_verify($password, $hash)) {
// password correct!
} else {
// password wrong!
}