https://php.watch/versions/7.4 PHP 7.4, the final release in the PHP 7.x series. PHP 7.4 brings typed properties, underscore numeric separator, and other minor improvements to PHP.
// 有限的 Limited 返回类型协变和参数类型逆变 classA{} classBextendsA{} classProducer{ publicfunctionmethod(): A{} } classChildProducerextendsProducer{ publicfunctionmethod(): B{} } // PHP74 // ok // // PHP73 // Fatal error: Declaration of ChildProducer::method(): B must be compatible with Producer::method(): A
// 以数组形式访问非数组,将会抛出 notic // null, bool, int, float or resource $i = 12; $i["a"]; // PHP74 // Notice: Trying to access array offset on value of type int // // PHP80 // Warning: Trying to access array offset on value of type int // // PHP73 ok
Deprecated Features 7.4
// 嵌套的三元运算必须明确地使用括号来指示运算的顺序 var_dump(1 ? 2 : 3 ? 4 : 5); // PHP74 // Deprecated: Unparenthesized `a ? b : c ? d : e` is deprecated. Use either `(a ? b : c) ? d : e` or `a ? b : (c ? d : e)` // int(4)
// Union types 联合类型 // ?T is same T|null // // - 类型只能出现一次 int|string|INT 否则报错 // - 使用 mixed 会报错 // - bool 与 false or true 不能混用 // - object 与 class 不能混用 // - iterable 与 array Traversable 不能混用 // - 使用 self、parent 或 static 都会导致错误
// match 表达式 // https://www.php.net/manual/en/control-structures.match.php // match 表达式必须是详尽,则会抛出 UnhandledMatchError。 $food = 'cake'; $return_value = match ($food) { 'apple' => 'This food is an apple', 'bar' => 'This food is a bar', 'cake' => 'This food is a cake', }; var_dump($return_value); // string(19) "This food is a cake"
// Nullsafe 方法和属性 // As of PHP 8.0.0, this line: $result = $repository?->getUser(5)?->name; // Is equivalent to the following code block: if (is_null($repository)) { $result = null; } else { $user = $repository->getUser(5); if (is_null($user)) { $result = null; } else { $result = $user->name; } }
// The WeakMap class has been added, accepts objects as keys, similar SplObjectStorage // https://www.php.net/manual/en/class.weakmap.php // https://www.php.net/manual/en/class.splobjectstorage.php // final class WeakMap implements ArrayAccess, Countable, IteratorAggregate $wm = newWeakMap(); $o = newStdClass; classA{ publicfunction__destruct() { echo"Dead!\n"; } } $wm[$o] = new A; var_dump(count($wm)); // int(1) unset($o); // Dead! // 销毁 var_dump(count($wm)); // int(0)