实验环境:https://onlinephp.io/ https://www.php.net/releases/8.3/en.php https://www.php.net/manual/en/migration83.php https://php.watch/versions/8.3 PHP 8.3 contains many new features, such as explicit typing of class constants, deep-cloning of readonly properties and additions to the randomness functionality.
New Features 8.3 // Typed class constants // Include class, trait, interface, enum trait TestTrait { final protected const string TEST = 'test'; } interface TestInterface { public const string TEST = 'test'; } enum TestEnum: string { public const string TEST = 'test'; } // Similar to return types, class constant types can also be "narrowed", or kept the same in a sub-class or an implementation. This follows LSP. class ParentClass { public const string|int VALUE = 'MyValue'; } class ChildClass extends ParentClass { public const string VALUE = 'MyValue'; } json_validate('[1, 2, 3]'); // true json_validate('{1, 2, 3]'); // false // Dynamic class constant and Enum member fetch support class Foo { const PHP = 'PHP 8.3'; } $searchableConstant = 'PHP'; echo constant(Foo::class . "::{$searchableConstant}"); echo Foo::{$searchableConstant}; // instead of `constant()` // Random extension // public function getFloat( // float $min, float $max, // \Random\IntervalBoundary $boundary = \Random\IntervalBoundary::ClosedOpen // ): float // // enum IntervalBoundary { // case ClosedOpen; // case ClosedClosed; // case OpenClosed; // case OpenOpen; // } $rng = new Random\Randomizer(); echo $rng->getFloat(0, 10, \Random\IntervalBoundary::OpenOpen); // 6.7810757668383 // Generate a random number in the range 0 <= and < 1: $rng = new Random\Randomizer(); echo $rng->nextFloat(); // 0.21185336351144 // Returns a random number sequence of a requested length ($length parameter), only containing a bytes from the requested series of bytes ($string parameter). $rng = new Random\Randomizer(); $chars = 'AEIOU'; echo $rng->getBytesFromString($chars, 1); // "E" echo $rng->getBytesFromString($chars, 5); // "AIIEO" // #[\Override] attribute // PHP enforces that the targeted class method must be overriding or implementing a parent/interface method. class ParentClass { protected function demo() {} } class ChildClass extends ParentClass { #[\Override] protected function demo() {} // ✅ 明确覆盖 #[\Override] protected function demmo() {} // ❌ Fatal error (拼写错误) } New Functions 8.3 // Pad a multibyte string to a certain length with another multibyte string echo mb_str_pad('中国', 6, '爱', STR_PAD_RIGHT) . "\n"; echo mb_str_pad('中国', 6, '爱', STR_PAD_LEFT) . "\n"; echo mb_str_pad('中国人', 6, '爱', STR_PAD_BOTH) . "\n"; // 中国爱爱爱爱 // 爱爱爱爱中国 // 爱中国人爱爱 Backward Incompatible Changes 8.3 // Assigning a negative index n to an empty array will now make sure that the next index is n + 1 instead of 0. $arr = []; $arr[-5] = 'a'; $arr[] = 'b'; var_dump($arr); // PHP8.3 → [-5 => 'a', -4 => 'b'] // PHP <8.3 → [-5 => 'a', 0 => 'b'] – EOF –
...