diff --git a/PHP/PHP8.1.md b/PHP/PHP8.1.md new file mode 100644 index 0000000..6987891 --- /dev/null +++ b/PHP/PHP8.1.md @@ -0,0 +1,91 @@ +PHP8.1在2021年11月25日发布了。又带来了很多很特性和性能改进。 + +## 枚举 +Enum 只支持整型和字符串两种类型 +```php +enum Status: int { + case SUCCESS = 0 + case ERROR = 1 +} + +function test (Status $status) { + +} +test(Status::SUCCESS) +``` + +### 枚举属性和方法 + +枚举有两个属性 `name` 、`value` +```php + $status->name; + $status->value; +``` +Enum 提供了 from () 方法来通过选项 value 的值来获取对应的选项 + +```php +dump(Status::from(0)); + +``` + +## 数组解包 +```php +$array_1 = [ + 'key1' => 'foo', + 'key2' => 'bar' +]; +$array_2 = [ + 'key3' => 'baz', + 'key4' => 'qux' +]; + +$array_unpacked = [...$array_1, ...$array_2]; +dd($array_unpacked); +``` +新增`array_is_list ` 判断是否是从 0 开始递增的数字数组 +```php +dump(array_is_list(['apple', 'orange'])); +``` + +## 类相关 + +### 只读属性readonly + +只读属性只允许初始化一次,修改 readonly 属性就会报错,只能在类的内部使用。 + +```php +class User { + public readonly int $uid; + + public function __construct(int $uid) { + $this->uid = $uid; + } +} +$user = new User(12) +$user->uid = 1;//error +``` +### final 类常量 + +```php +class Foo { + final public const TEST = '1'; +} + +``` + +## 函数相关 + +1. First-class Callable + +```php +$callable = strtoupper(...); +echo $callable('hello, world') . PHP_EOL; +``` +2. Never 返回类型 + +```php +function redirect(string $url): never { + header('Location: ' . $url); + exit(); +} +``` diff --git a/PHP/PHP8.2.md b/PHP/PHP8.2.md new file mode 100644 index 0000000..c0d6206 --- /dev/null +++ b/PHP/PHP8.2.md @@ -0,0 +1,72 @@ +## PHP8.2的变化 +- [PHP8.2](https://www.php.net/releases/8.2/zh.php) +### 只读类 +使用`readonly` 修饰类名 +```php +title = $title; + $this->status = $status; + } +} +``` +### 析取范式 (DNF)类型 +简单的理解,就是定义参数支持交集和并集,'组合并集和交集类型时,交集类型必须用括号进行分组' +```php +class Foo { + public function bar((A&B)|null $entity) { + return $entity; + } +} +``` +### 允许 null、false 和 true 作为独立类型 +```php + +function f(): false { + return false; +} +function f1(): true { + return true; +} +function f2(): null { + return null; +} +``` +### 新的“随机”扩展 +`\Random\Randomizer` 类提供了一个高级接口来使用引擎的随机性来生成随机整数、随机排列数组或字符串、选择随机数组键等。 + +### Traits 中允许常量 +```php +trait T +{ + public const CONSTANT = 1; +} +``` +### 弃用动态属性 +动态属性的创建已被弃用,以帮助避免错误和拼写错误,除非该类通过使用 `#[\AllowDynamicProperties]` 属性来选择。`stdClass` 允许动态属性。 +__get/__set 魔术方法的使用不受此更改的影响。 +```php +class User +{ + public $name; +} + +$user = new User(); +$user->last_name = 'Doe'; // Deprecated notice + +$user = new stdClass(); +$user->last_name = 'Doe'; // Still allowed +``` + +## 弃用和向后不兼容 +- 弃用 ${} 字符串插值。 +- 弃用 utf8_encode 和 utf8_decode 函数。 +- DateTime::createFromImmutable 和 DateTimeImmutable::createFromMutable 方法暂定返回类型为 static。 +- strtolower 和 strtoupper 函数不再对语言环境敏感。