Во-первых, мы говорим о PHP 7.4.10, но любая общая информация приветствуется!
Обобщенный вопрос: я хотел бы определить статический метод в абстрактном классе таким образом, чтобы метод можно было вызывать публично только из дочерних классов, расширяющих абстрактный класс, но не из самого абстрактного класса. Извините, если я здесь слишком простой, но я буквально часами искал ответ и даже не могу найти никаких обсуждений по этой теме.
Рассмотрим следующий пример (пояснение в комментариях). Я хочу иметь возможность звонить Apple::printName()
и Pear::printName()
, но не Fruit::printName()
.
abstract class Fruit
{
/*
* Oblige every child class to define a string name, nothing unusual
*/
protected abstract static function name() : string;
/*
* The problem is with the access modifier of this method here
***
* If it is public, everything is fine with Apple::printName() and Pear::printName(),
* but one can call Fruit::printName() from outside,
* resulting in PHP Error: Cannot call abstract method Fruit::name()
* this is still sort of okay, since an error will be thrown anyway,
* but I don't want the runtime to even enter the method's body
* I'd like to get an access restriction error.
***
* If it is protected, then we automatically can't call Apple::printName nor Pear::printName()
***
* So, is there a way to define the parent static method only publicly accessible from child classes without copying code?
*/
public static function printName()
{
return "My name is: " . static::name();
}
}
class Apple extends Fruit
{
protected static function name() : string
{
return "apple";
}
}
class Pear extends Fruit
{
protected static function name() : string
{
return "pear";
}
}
echo Apple::printName(); //prints "My name is: apple"
echo Pear::printName(); //prints "My name is: pear"
echo Fruit::printName(); //PHP Error: Cannot call abstract method Fruit::name() at line...
Я также открыт для любых альтернативных подходов к тому, как можно добиться желаемого поведения.