PHP 7.4 引入了多项重要特性,以下是主要亮点:
1. 类型属性(Typed Properties)
支持在类属性中声明类型:
php
class User {
public int $id;
public string $name;
}
- 类型包括:
int,float,string,bool,array,object,iterable,self等。 - 未初始化或类型不匹配会抛出
TypeError。
2. 箭头函数(Arrow Functions)
简化闭包语法,自动绑定外部变量:
php
$factor = 2;
$nums = array_map(fn($n) => $n * $factor, [1, 2, 3]);
// 结果: [2, 4, 6]
- 仅支持单行表达式,无需
use显式捕获变量。
3. 数组解包(Spread Operator in Arrays)
支持 ... 展开数组:
php
$parts = [1, 2];
$merged = [...$parts, 3, 4]; // [1, 2, 3, 4]
4. 空合并赋值运算符(Null Coalescing Assignment)
简化默认值赋值:
php
$data['key'] ??= 'default';
// 等价于: $data['key'] = $data['key'] ?? 'default';
5. 预加载(Preloading)
通过 opcache.preload 在服务启动时预加载脚本,提升性能:
ini
; php.ini 配置
opcache.preload=/path/to/preload.php
6. FFI(Foreign Function Interface)
在 PHP 中直接调用 C 函数/数据结构:
php
$ffi = FFI::cdef("int printf(const char *format, ...);", "libc.so.6");
$ffi->printf("Hello %s!\n", "PHP");
7. 弱引用(Weak References)
允许对象被垃圾回收,避免内存泄漏:
php
$obj = new stdClass;
$weakRef = WeakReference::create($obj);
var_dump($weakRef->get()); // 对象存在
unset($obj);
var_dump($weakRef->get()); // null
8. 数值分隔符(Numeric Literal Separator)
提高大数字可读性:
php
$million = 1_000_000;
$hex = 0xCAFE_F00D;
9. 其他改进
mb_str_split():多字节字符串分割。password_hash()支持弱算法检测。strip_tags()支持数组标签名。- 弃用
ext/hash中的旧别名(如mhash)。
10. 性能优化
- 执行效率比 PHP 7.3 提升约 15-20%。
- 内存消耗进一步降低。
注意:PHP 7.4 已于 2022 年 11 月结束官方支持,建议升级至 PHP 8.x 以获取长期维护。