Home > Article > Backend Development > How Should I Handle Return Type Deprecation Notices in PHP?
Since PHP 7.0, return types for functions and methods have been available. This forms a contract that other code can rely on.
For example:
<code class="php">class Base { public function getList(): Iterator { // ... } } // Calling code: $foo = new Base(); var_dump($foo instanceOf Base); // true var_dump($foo->getList() instanceOf Iterator); // true</code>
When extending a class, a more specific return type can be defined (covariance). However, specifying a different return type or no return type is not allowed.
Adding return types to existing classes or interfaces requires changes in extending or implementing classes. With the introduction of Union Types in PHP 8.0, return types were documented but not enforced as errors. Instead, a deprecation notice was added.
Conflicting code that needs to support multiple PHP versions and pre-8.0 return types led to the development of the #[ReturnTypeWillChange] attribute. When added to a method, it suppresses the deprecation notice in PHP 8.1. This gives time to rectify the issue before PHP 9.0, where internal return types may be enforced.
Decide your course of action:
If it's safe to change the return type:
If you need to support older PHP versions or un-updated code:
The above is the detailed content of How Should I Handle Return Type Deprecation Notices in PHP?. For more information, please follow other related articles on the PHP Chinese website!