我想更新我们当前在 PHP 7.2 上运行的项目,但我遇到了一个无法轻松解决的问题。
public function getCategories($type){...}
//In another file that dosent implements Category
$categories = Category::getCategories('xxx');
我遇到的问题是,在 PHP 8 中你不能再静态调用非静态函数,但我也不能将它重写为
$categories = (new Category)->getCategories('xxx');
,因为它是一个抽象类。
作为临时解决方案,我考虑将 getCategories 转换为静态方法。但是,我担心此更改可能会对项目产生潜在的副作用。
有人对在 PHP 8 中处理这种情况有建议吗?理想情况下,我正在寻找一种解决方案,避免修改方法的静态/非静态状态,同时仍然遵守 PHP 8 更严格的标准。
我想不出您在 PHP/7 中尚未遇到的任何副作用。该方法已经被静态调用,因此如果它碰巧尝试访问类实例,它就已经崩溃了:
abstract class Category
{
public $foo = [1, 2, 3];
public function getCategories($type)
{
return $this->foo;
}
}
class ChildCategory extends Category
{
}
// This works fine
$categories = (new ChildCategory())->getCategories('xxx');
var_dump($categories);
// Fatal error: Uncaught Error: Using $this when not in object context
$categories = Category::getCategories('xxx');
var_dump($categories);
如果它没有崩溃,那就证明它的核心是静态的,所以你可以将其正式化:
abstract class Category
{
static function getCategories($type)
{
return [1, 2, 3];
}
}
class ChildCategory extends Category
{
}
$categories = (new ChildCategory())->getCategories('xxx');
var_dump($categories);
$categories = Category::getCategories('xxx');
var_dump($categories);
请注意,从类实例调用静态方法是完全可以的。