您现在的位置是:首页 > PHP框架交流PHP框架交流

PHP8.0新特性(4) 联合类型

上善若水2024-03-05 09:48:48【PHP框架交流】 83人已围观

简介熟悉PHP8.0的新特性,联合类型,现在定义好联合类型后,创建联合类型不对的时候会抛出异常了。联合类型 相较于以前的 PHPDoc 声明类型的组合, 现在可以用原生支持的联合类型声明取而代之,并在运行

熟悉PHP8.0的新特性,联合类型,现在定义好联合类型后,创建联合类型不对的时候会抛出异常了。
联合类型 相较于以前的 PHPDoc 声明类型的组合, 现在可以用原生支持的联合类型声明取而代之,并在运行时得到校验。

class Number {
  public function __construct(
    private int|float $number//PHP8.0新特性构造器属性提升写法
  ) {}
}

1.输入数字

$n = new Number(10); // TypeError
var_dump($n);
#打印结果
class Number#1 (1) {
  private int|float $number =>
  int(10)
}

2.输入小数

$n = new Number(10); // TypeError
var_dump($n);
#打印结果
class Number#1 (1) {
  private int|float $number =>
  double(10.5)
}

3.输入带引号的小数

$n = new Number("10.5"); // TypeError
var_dump($n);
#打印结果
class Number#1 (1) {
  private int|float $number =>
  double(10.5)
}

4.输入带引号的整数

$n = new Number("10"); // TypeError
var_dump($n);
#打印结果
class Number#1 (1) {
  private int|float $number =>
  int(10)
}

5.输入带非数字的字符串

$n = new Number("10a"); // TypeError
var_dump($n);

打印结果,报错!

Fatal error: Uncaught TypeError: Number::__construct(): Argument #1 ($number) must be of type int|float, string given, called in D:\phpstudy_pro\WWW\testphp8_0\PHP8_0\union_types.php on line 10 and defined in D:\phpstudy_pro\WWW\testphp8_0\PHP8_0\union_types.php on line 5

TypeError: Number::__construct(): Argument #1 ($number) must be of type int|float, string given, called in D:\phpstudy_pro\WWW\testphp8_0\PHP8_0\union_types.php on line 10 in D:\phpstudy_pro\WWW\testphp8_0\PHP8_0\union_types.php on line 5

Tags: PHP8.0

很赞哦! (0)

文章评论

站点信息

  • 建站时间:2019-10-24
  • 网站程序:Thinkphp6 Layui
  • 文章统计247篇文章
  • 标签管理标签云
  • 统计数据cnzz统计
  • 微信公众号:扫描二维码,关注我们