/

PHP Migrating 8.1 to 8.2

PHP 8.2 brings type-system improvements for expressive and fine-grained type-safety, readonly classes, sensitive parameter redaction support, new random extension, and many new features along with several changes to streamline and modernize PHP language.

New Features 8.2

// Readonly Classes
// Complete class properties become immutable when declared readonly
readonly class User {
public function __construct(public string $username, public string $email) {
}
}

// All properties automatically become readonly
$user = new User('john_doe', 'john@example.com');
$user->email = 'new@example.com';
// Fatal error: Uncaught Error: Cannot modify readonly property User::$email
// Combine union and intersection types using Disjunctive Normal Form
// 析取范式,允许通过 |(联合)和 &(交叉)运算符组合类型
function process((Countable&Iterator)|null $item) {
return $item;
}
// Use null, true, false as independent types
function alwaysFalse(): false {}
function alwaysNull(): null {}
function alwaysTrue(): true {}
// Define constants directly in traits
trait NetworkTrait {
public const TIMEOUT = 60;
}
// Hide sensitive data in stack traces
function hashPassword(#[\SensitiveParameter] string $password) {
debug_print_backtrace();
}
hashPassword('secret123');
// Before #0 /home/user/scripts/code.php(7): hashPassword('secret123')
// PHP8.2 #0 /home/user/scripts/code.php(7): hashPassword(Object(SensitiveParameterValue))
// Consolidated RNG functions with OOP interface
$randomizer = new \Random\Randomizer();
echo $randomizer->getInt(1, 100); // Random integer

New Functions 8.2

// Parses any data size recognized by PHP INI values
ini_parse_quantity('256M'); // 268435456

Deprecated Features 8.2

// ${var} String Interpolation Deprecated
$name = 'Li';
echo "Hello ${name}"; // should be `{$name}`
// Deprecated: Using ${var} in strings is deprecated, use {$var} instead
$var = 'name';
echo "Hello ${$var}"; // should be `{$$var}`
// Deprecated: Using ${expr} (variable variables) in strings is deprecated, use {${expr}}

– EOF –