PHP 7: Maintaining and Upgrading Legacy Apps · Upgrading from PHP 7 to PHP 8
Deprecations in PHP 8.1–8.4
Dynamic properties, null to non-nullable internal parameters, implicit nullable types and more.
Later 8.x versions deprecate patterns common in legacy code. 8.1: passing null to non-nullable internal function parameters (strlen(null)), Serializable without __serialize. 8.2: dynamic properties (assigning undeclared properties) unless the class has #[AllowDynamicProperties], ${var} string interpolation. 8.4: implicitly nullable parameters (Type $x = null must become ?Type $x = null). Deprecations become errors in PHP 9, so fix them now.
<?php
class Legacy {
public function __construct() {
$this->cache = []; // 8.2: Deprecated: Creation of dynamic property
}
}
// Fix: declare the property
class Fixed {
private array $cache = [];
}
strlen($maybeNull); // 8.1: Deprecated when $maybeNull is null
strlen($maybeNull ?? ''); // fix
function find(Logger $logger = null) {} // 8.4: implicitly nullable — deprecated
function find2(?Logger $logger = null) {} // fix
Common pitfalls
- Silencing deprecations instead of logging and fixing them.
- Adding
#[AllowDynamicProperties]everywhere rather than declaring properties. - Not testing with
error_reporting=E_ALLin CI.
Key points
- Declare properties; avoid dynamic ones
- Handle null before calling internal functions
- Fix deprecations before PHP 9
Further reading: PHP manual: PHP 8.2 deprecations
Practice questions
What is a dynamic property and why was it deprecated?
Answer
A property created by assigning to an undeclared name ($this->foo = 1). It hides typos and makes classes unpredictable; PHP 8.2 deprecates it unless the class opts in with #[AllowDynamicProperties] or uses __set.
How do you fix 'Implicitly marking parameter as nullable is deprecated'?
Answer
Change Type $x = null to ?Type $x = null (or Type|null). This is a PHP 8.4 deprecation.
Open in the app to mark lessons complete, take notes and track your progress.