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();
3
Answers
Change
Person
to__construct
https://3v4l.org/Ke39i
This is not a good practice so far and deprecated in PHP. You will be in trouble if you are using the constructor name as like method name in future. Better constructor use as
__construcotr
.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.