PHP is one of the most popular and widely used programming languages for web development. It powers millions of websites, from blogs and e-commerce platforms to APIs and web servers. PHP has been evolving constantly since its inception in 1995, adding new features, improving performance, and enhancing security. In this blog post, we will explore the current state of PHP development, featuring the releases of PHP 8.2 and the upcoming 8.3 version, highlighting the key new features, and providing an outlook on the next versions ahead.
PHP 8.2: The Latest Stable Release
PHP 8.2 was released on December 8, 2022, as the latest stable version of the language. It brings several improvements and new features that aim to make PHP more expressive, consistent, and reliable. Some of the notable features of PHP 8.2 are:
- Readonly classes: PHP 8.2 introduces the
readonly
modifier for class properties, which prevents them from being modified after initialization. This can help enforce immutability and avoid accidental mutations of data. Readonly properties can only be initialized in the constructor or by a default value. For example:
class Point {
public readonly int $x;
public readonly int $y;
public function __construct(int $x, int $y) {
$this->x = $x;
$this->y = $y;
}
}
$p = new Point(1, 2);
$p->x = 3; // Error: Cannot modify readonly property Point::$x
- DNF types: PHP 8.2 supports disjunctive normal form (DNF) types, which allow combining union and intersection types with parentheses. This can help express more complex type constraints and improve type inference. For example:
function foo((A|B)&C $x) {...}
foo(new A()); // Error: Argument 1 passed to foo() must be an instance of (A|B)&C, A given
foo(new C()); // Error: Argument 1 passed to foo() must be an instance of (A|B)&C, C given
foo(new A&C()); // OK
foo(new B&C()); // OK
- Null, false, and true types: PHP 8.2 adds support for
null
,false
, andtrue
as standalone types, which can be used in union types, return types, and parameter types. This can help express more precise type contracts and avoid unnecessary null checks. For example:
function bar(): int|false {...}
$result = bar();
if ($result !== false) {
echo $result + 1; // OK, $result is int
}
- Sensitive parameter redaction: PHP 8.2 introduces the
#[SensitiveParameter]
attribute, which can be used to mark parameters that contain sensitive information, such as passwords, tokens, or credit card numbers. When a function with such parameters throws an exception or triggers an error, the parameter values will be replaced with asterisks in the stack trace. This can help prevent leaking sensitive data in logs or error messages. For example:
function baz(#[SensitiveParameter] string $password) {...}
baz("secret"); // Error: baz(): Failed opening required 'secret' (include_path='...')
// Stack trace:
// #0 {main}
// thrown in ... on line ...
// baz(********)
- New random extension: PHP 8.2 introduces a new extension called
random
, which provides a new object-oriented API to random number generation. The extension offers several classes (Engine
s) that implement different algorithms for generating random numbers, such asMersenneTwisterEngine
,XorShiftEngine
, andChaCha20Engine
. The engines can be seeded and stored in objects, allowing for multiple independent and reproducible sequences. The extension also provides aRandomizer
class, which offers high-level methods to generate random integers, floats, strings, arrays, and more. For example:
use Random\{Randomizer, MersenneTwisterEngine};
$engine = new MersenneTwisterEngine(1234); // Create a seeded engine
$randomizer = new Randomizer($engine); // Create a randomizer with the engine
echo $randomizer->getInt(1, 10); // 4
echo $randomizer->getFloat(); // 0.19151945037889222
echo $randomizer->getString(8); // "fUvZ9tHb"
echo $randomizer->getArrayElement(["a", "b", "c"]); // "b"
PHP 8.2 also includes many other features, such as typed class constants, fetch class constant dynamically syntax, override attribute, new mysqli methods, new ZipArchive methods, and more. Additionally, PHP 8.2 deprecates some legacy features, such as dynamic properties, utf8_encode and utf8_decode functions, and MT_RAND_PHP constant. For a full list of changes, you can read the changelog or the migration guide.
PHP 8.3: The Upcoming Release
PHP 8.3 is the next minor release of the language, which is scheduled to be released on November 23, 2023. It is currently in the release candidate stage, which means that no new features will be added, and only bug fixes and stability improvements will be made. PHP 8.3 brings several new features and enhancements to the language, such as:
- Typed class constants: PHP 8.3 allows declaring types for class constants, which can help enforce type safety and document the expected values. Typed class constants can be public, protected, or private, and can have any type that is valid for a property. For example:
class Foo {
public const int MAX_VALUE = 100;
private const string NAME = "Foo";
}
echo Foo::MAX_VALUE; // 100
echo Foo::NAME; // Error: Cannot access private const Foo::NAME
- Granular DateTime exceptions: PHP 8.3 introduces new exception classes for the DateTime extension, which extend from the base
DateTimeException
class. These exceptions are more specific and descriptive than the genericException
class that was used before. For example,DateTimeParseException
is thrown when a date or time string cannot be parsed,DateTimeArithmeticException
is thrown when an arithmetic operation on a date or time fails, andDateTimeZoneException
is thrown when a time zone is invalid or not found. These exceptions can help developers to handle errors more gracefully and provide better feedback to users. For example:
try {
$date = new DateTime("invalid");
} catch (DateTimeParseException $e) {
echo "Invalid date format: " . $e->getMessage();
}
- Fallback value support for PHP INI environment variable syntax: PHP 8.3 adds support for fallback values in the PHP INI environment variable syntax, which allows specifying a default value to use when an environment variable is not set or empty. The syntax is
${ENV_VAR_NAME:-default_value}
, whereENV_VAR_NAME
is the name of the environment variable, anddefault_value
is the value to use if the variable is not set or empty. This can help provide more flexibility and robustness when configuring PHP settings via environment variables. For example:
; php.ini
memory_limit = ${PHP_MEMORY_LIMIT:-256M}
- Command line linter variadic input: PHP 8.3 allows passing multiple filenames to the command line linter (
php -l
), which can check the syntax of PHP files without executing them. This can help speed up the linting process and avoid running multiple commands. For example:
php -l foo.php bar.php
No syntax errors detected in foo.php
No syntax errors detected in bar.php
- New classes, interfaces, and functions: PHP 8.3 adds several new classes, interfaces, and functions to various extensions, such as DOM, Intl, LDAP, mbstring, POSIX, Reflection, Socket, String, Stream, and Zip. Some of the notable additions are:
DOMElement::getAttributeNames()
,DOMElement::insertAdjacentElement()
,DOMElement::insertAdjacentText()
,DOMElement::toggleAttribute()
,DOMNode::contains()
,DOMNode::getRootNode()
,DOMNode::isEqualNode()
,DOMNameSpaceNode::contains()
, andDOMParentNode::replaceChildren()
methods for the DOM extension, which provide more functionality and compatibility with the DOM Living Standard.IntlCalendar::setDate()
,IntlCalendar::setDateTime()
,IntlGregorianCalendar::createFromDate()
, andIntlGregorianCalendar::createFromDateTime()
methods for the Intl extension, which allow creating and manipulating calendars with date and time values.ldap_connect_wallet()
andldap_exop_sync()
functions for the LDAP extension, which allow connecting to an LDAP server using Oracle Wallet authentication and performing a synchronization operation using the LDAP Sync protocol, respectively.mb_str_pad()
function for the mbstring extension, which pads a multibyte string to a given length with another string.posix_sysconf()
,posix_pathconf()
,posix_fpathconf()
, andposix_eaccess()
functions for the POSIX extension, which allow querying system and path configuration