PHP8.2 特性及变更

six

PHP8.2 将于2022年12月8日发布,特性及变更如下

新功能

SensitiveParameter 属性

新增 #[\SensitiveParameter] 属性用于编辑回溯中的敏感数据。
新增error_log_mode INI 指令,允许设置错误日志的权限。

常量表达式中的枚举属性

现在可以在常量表达式中获取枚举属性。

类型系统提升

现在可以使用 null 和 false 作为独立类型。

新增 true 类型。

现在可以组合交集和联合类型。类型需要用 DNF 编写。

Trait 中常量

现在可以在 trait 中定义常量。

只读类

新增对只读类的支持。

readonly class Foo
{
    public $bar = 1;
}

弃用的功能

动态属性的使用

弃用动态属性创建,除非类选择使用 #[\AllowDynamicProperties] 注解。stdClass 允许动态属性。__get()/__set() 魔术方法不受此更改的影响。解决动态属性弃用警告,可以通过以下方式:

  • 声明属性(首选)。
  • #[\AllowDynamicProperties] 添加到 #[\AllowDynamicProperties](这也适用于所有子类)。
  • 如果需要将附加数据于不属于自己的对象相关联,则使用 WeakMap

Relative callables

弃用 $callable() 语法不接受的可调用对象(但 call_user_func() 接受)。尤其是:

  • "self::method"
  • "parent::method"
  • "static::method"
  • ["self", "method"]
  • ["parent", "method"]
  • ["static", "method"]
  • ["Foo", "Bar::method"]
  • [new Foo, "Bar::method"]
    这不会影响正常方法调用,比如 "A::method"["A", "method"]

"${var}" 和 "${expr}" 样式插值

弃用字符串插值的 "${var}""${expr}" 样式。 Use "$var"/"{$var}" and "{${expr}}", respectively.

总结

总体与PHP8.1变化不大,比较大的一个兼容性问题是类的动态属性默认不再支持。例如:

class Foo
{
}
$foo = new Foo;
// 这里给类动态添加属性将报错
$foo->someVaue = 'some data';

不过可以通过给类增加#[\AllowDynamicProperties] 注解解决,例如

#[\AllowDynamicProperties]
class Foo
{
}
$foo = new Foo;
// 不报错
$foo->someVaue = 'some data';
3114 5 0
5个回答

powerbowen

get

  • 暂无评论
admin

ok

可以在说下 fiber()->then 吗

  • 暂无评论
又有心跳

这个看不懂,求指教原先是啥
弃用 $callable() 语法不接受的可调用对象(但 call_user_func() 接受)。尤其是:

  • "self::method"
  • "parent::method"
  • "static::method"
  • ["self", "method"]
  • ["parent", "method"]
  • ["static", "method"]
  • ["Foo", "Bar::method"]
  • [new Foo, "Bar::method"]
    这不会影响正常方法调用,比如 "A::method" 或 ["A", "method"]。
  • luohonen 2022-12-08

    本身就很少用到,不影响的

  • 又有心跳 2022-12-09

    哈哈,我百度了,确实,就是写的明确些,
    "self::method" -> self::class . "::method"

    "parent::method" -> parent::class . "::method"

    "static::method" -> static::class . "::method"

    ["self", "method"] -> [self::class, "method"]

    ["parent", "method"] -> [parent::class, "method"]

    ["static", "method"] -> [static::class, "method"]

    // 下面2个写法无实际意义

    ["Foo", "Bar::method"] -> "Foo::Bar::method"

    [new Foo, "Bar::method"] -> "Foo::Bar::method"

artisan

强大

  • 暂无评论
Tinywan

Get

  • 暂无评论
年代过于久远,无法发表回答
🔝