I want to update our current project that runs on PHP 7.2 but I got an issue that I cant resolve easily.
public function getCategories($type){...}
//In another file that dosent implements Category
$categories = Category::getCategories('xxx');
The issue I have is, that in PHP 8 you cant call non-static functions anymore staticly, but I also can’t rewrite it to $categories = (new Category)->getCategories('xxx');
because its an abstract class.
As a temporary solution, I’ve considered converting getCategories into a static method. However, I’m concerned about potential side effects this change might have on the project.
Does anyone have a suggestion for handling this situation in PHP 8? Ideally, I’m looking for a solution that avoids modifying the method’s static/non-static status while still complying with PHP 8’s stricter standards.
2
Answers
I can’t think of any side effect you aren’t already hitting in PHP/7. The method is already being called statically, so if it happens to try to access a class instance, it would be already crashing:
Demo
If it isn’t crashing, that proves it’s static at its core, so you can just make it official:
Demo
Note that is perfectly fine to invoke a static method from a class instance.
You can call a non-static function from an abstract class in PHP 8 using anonymous classes extending the abstract class.
Demo