Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make PHP version 8 support constructor with same name as class?

Tags:

php

php-8

I have a legacy project being migrated to PHP version 8, but the new PHP version doesn't support class constructor named based on the class name, which worked in old versions.

I want classes like this to continue working:

class Person {
    
    private $fname;
    private $lname;
    
    // Constructor same class name here
    public function Person($fname, $lname) {
        $this->fname = $fname;
        $this->lname = $lname;
    }
    
    // public method to show name
    public function showName() {
        echo "My name is: " . $this->fname . " " . $this->lname . "<br/>"; 
    }
}

// creating class object
$john = new Person("John", "Wick");
$john->showName();
like image 782
Meas Avatar asked Dec 31 '25 16:12

Meas


2 Answers

This isn't a case of a setting that you can turn back on, I'm afraid, the functionality was permanently removed from PHP. It might be possible to write some kind of extension which emulated the old behaviour, but it's going to be a lot more work in the long run than doing a one-off fix to all your existing files.

Your best bet is probably to use a tool such as Rector which can automate the upgrade process. In this case, using the Php4ConstructorRector rule looks like it should do it all for you.

like image 73
IMSoP Avatar answered Jan 02 '26 06:01

IMSoP


Change Person to __construct

public function __construct($fname, $lname) {
    $this->fname = $fname;
    $this->lname = $lname;
}

https://3v4l.org/Ke39i

like image 43
Rain Avatar answered Jan 02 '26 05:01

Rain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!