
Methods with the same name as their class will not be constructors in a future version of PHP
This warning message occurs because class constructors can’t have the same name as their class. You can fix this by changing it to __construct()
.
- Grab your favorite code editor and search for class definitions across your project;
- Check for constructor methods with the same name as the class and change it to
__construct
.
Your modifications should look like this:
class Foo { - public function Foo() + public function __construct() { } }
That’s it, it’s as simple as that.
But did you know the story behind this change?
In PHP 4, as you know, a constructor was declared with the same name as its class. It was still working in PHP 5, was deprecated in PHP 7.0, and removed in PHP 8.0. That is why you must rename your constructors before migrating to version 8 or greater.
For posterity, you can read more about it on the official PHP documentation: PHP deprecated features in version 7.0.x
You can also see the PHP RFC that led to this: PHP RFC: Remove PHP 4 Constructors
Did you like this article? Then, keep learning:
- Stay updated with upcoming PHP 8.4 features and release timeline
- Explore the best PHP blogs to keep your PHP knowledge fresh in 2024
- Discover best PHP packages to use in 2024 for enhanced productivity
- Learn how to check your PHP version multiple ways, important for upgrades
- Discover tools to manage PHP extensions versioning for compatibility
- Understand the new Override attribute added in PHP 8.3
- Learn about PHP 8.3 changes, useful before upgrading your PHP version
- Get insight into PHP 9.0 planned breaking changes and features
- Improve your code safety using PHP Enumerations (Enums)
- Master PHP error reporting to debug issues like constructor warnings effectively