PHP8.1新特性之&参数类型检查

作者: 温新

分类: 【PHP基础】

阅读: 2615

时间: 2022-02-15 15:18:59

hi,我是温新, 一名PHPer

PHP8.1中使用&进行实现多个类型的安全检查。关于类型检查如下:返回的结果必须是字符串。

<?php
    
class Test
{
    public function getA():string
    {
        return 'hello world';
    }
}

PHP8.1 &多类型检查

<?php

interface Timer{}

interface Dater {}

class A implements Timer, Dater {}

class B implements Dater {}

class Test {
    // 该方法对类型进行的限制
    // $res的类型必须要实现Timer和Dater这两个接口
    // 否则就会报错
	public static function index(Timer&Dater $res)
	{
		var_dump($res);
	}
}

Test::index(new A());

使用|可以实现一个

基于上面的案例改动来进行测试

<?php
    
class Test {
	public static function index(Timer|Dater $res)
	{
		var_dump($res);
	}
}

Test::index(new B());

&联合检查,两个都必须实现,否则会报错

class Test {
	public static function index(Timer&Dater $res)
	{
		var_dump($res);
	}
}

Test::index(new B());

报错信息:Fatal error: Uncaught TypeError: Test::index(): Argument #1 ($res) must be of type Timer&Dater, B given, called in

基础是基石

请登录后再评论