Get your next remote job on LaraJobs.
PHP

Methods with the same name as their class will not be constructors in a future version of PHP

Benjamin Crozat
Modified on Nov 23, 2022 0 comments Edit on GitHub
Methods with the same name as their class will not be constructors in a future version of PHP

Introduction

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().

  1. Grab your favorite code editor and search for class definitions across your project;
  2. 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() // [tl! --]
    public function __construct() // [tl! ++]
    {
    }
}

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

Wait, there's more!

Be the first to comment!

Get help or share something of value with other readers!

Great deals for enterprise developers
  • ZoneWatcher
    Get instant alerts on DNS changes across all major providers, before your customers notice.
    25% off for 12 months using the promo code CROZAT.
    Try ZoneWatcher for free
  • Quickly build highly customizable admin panels for Laravel projects.
    20% off on the pro version using the promo code CROZAT.
    Try Backpack for free
  • Summarize and talk to YouTube videos. Bypass ads, sponsors, chit-chat, and get to the point.
    Try Nobinge →
  • Monitor the health of your apps: downtimes, certificates, broken links, and more.
    20% off the first 3 months using the promo code CROZAT.
    Try Oh Dear for free
  • Keep the customers coming; monitor your Google rankings.
    30% off your first month using the promo code WELCOME30
    Try Wincher for free →
The latest community links
- / -