介绍php7.3到php7.4新特性

介绍php7.3到php7.4新特性,第1张

介绍php7.3到php7.4新特性

1、对象属性现在支持类型申明

<?php
class User {
    public int $id;
    public string $name;
}
?>

上列例子中将会强制转化$id为integer类型,$name为字符串类型

推荐(免费):PHP7

2、箭头函数

现在箭头函数会提供一个短语法用来定义那些在作用域内值申明不明确的函数

<?php
$factor = 10;
$nums = array_map(fn($n) => $n * $factor, [1, 2, 3, 4]);
// $nums = array(10, 20, 30, 40);
?>

3、有限返回类型协方差和参数类型协方差(谷歌翻译的)

下列代码将会运行

<?php
class A {}
class B extends A {}

class Producer {
    public function method(): A {}
}
class ChildProducer extends Producer {
    public function method(): B {}
}
?>

仅当使用自动加载时,才提供完全差异支持。 在单个文件内,只能使用非循环类型引用,因为所有类在被引用之前都必须可用

4、空合并分配运算符

<?php
$array['key'] ??= computeDefault();
// is roughly equivalent to
if (!isset($array['key'])) {
    $array['key'] = computeDefault();
}
?>

5、Unpacking inside arrays(谷歌翻译是 在数组内部解包,看这不对,先用英文吧)

<?php
$parts = ['apple', 'pear'];
$fruits = ['banana', 'orange', ...$parts, 'watermelon'];
// ['banana', 'orange', 'apple', 'pear', 'watermelon'];
?>

6、数值字符分隔符

数字字符可以在数字之间包含下划线。

<?php
6.674_083e-11; // float
299_792_458;   // decimal
0xCAFE_F00D;   // hexadecimal
0b0101_1111;   // binary
?>

7、弱参考(Weak references)

弱参考允许编程人员保留对不能防止被销毁的对象的参考(Weak references allow the programmer to retain a reference to an object that does not prevent the object from being destroyed.)

8、允许__toString()的异常

现在可以通过__toString()抛出异常,在之前的版本这会导致一个致命错误,字符串转换中现有的可导致致命错误已转换为抛出异常。

剩下的扩展以后再看

以上就是介绍php7.3到php7.4新特性的详细内容,

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/680073.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-20
下一篇 2022-04-20

发表评论

登录后才能评论

评论列表(0条)

保存