PHP 8.3版本已发布更新。注意到的是:PHP 8.0 的生命周期即将结束。早在 2022 年 11 月 26 日,PHP 8.0 结束了积极支持,而安全支持也将在 PHP 8.3 正式发布三天后 ——2023 年 11 月 26 日停止。
PHP 8.3 的主要新特性:
类型化类常量
// PHP < 8.3interface I { // We may naively assume that the PHP constant is always a string. const PHP = 'PHP 8.2';}
class Foo implements I { // But implementing classes may define it as an array. const PHP = [];}// PHP 8.3interface I { const string PHP = 'PHP 8.3';}
class Foo implements I { const string PHP = [];}
// Fatal error: Cannot use array as value for class constant// Foo::PHP of type string
动态获取类常量
// PHP < 8.3class Foo { const PHP = 'PHP 8.2';}
$searchableConstant = 'PHP';
var_dump(constant(Foo::class . "::{$searchableConstant}"));// PHP 8.3class Foo { const PHP = 'PHP 8.3';}
$searchableConstant = 'PHP';
var_dump(Foo::{$searchableConstant});
只读属性深拷贝
readonly属性现在可以在魔术方法__clone中被修改一次,以此实现只读属性的深拷贝。
// PHP class PHP { public string $version = '8.2';}
readonly class Foo { public function __construct( public PHP $php) {}
public function __clone(): void { $this->php = clone $this->php; }}
$instance = new Foo(new PHP());$cloned = clone $instance;
// Fatal error: Cannot modify readonly property Foo::$php
// PHP 8.3class PHP { public string $version = '8.2';}
readonly class Foo { public function __construct( public PHP $php) {}
public function __clone(): void { $this->php = clone $this->php; }}
$instance = new Foo(new PHP());$cloned = clone $instance;
$cloned->php->version = '8.3';
新增json_validate()函数
json_validate()可以检查一个字符串是否为语法正确的 JSON,比json_decode()更有效。
// PHP < 8.3function json_validate(string $string): bool { json_decode($string);
return json_last_error() === JSON_ERROR_NONE;}
var_dump(json_validate('{ "test": { "foo": "bar" } }')); // true
// PHP 8.3var_dump(json_validate('{ "test": { "foo": "bar" } }')); // true
领取专属 10元无门槛券
私享最新 技术干货