【发布时间】:2021-02-21 17:58:55
【问题描述】:
首先,我们谈论的是 PHP 7.4.10,但任何一般的英特尔都可以使用!
总结问题:我想在抽象类中定义一个静态方法,该方法只能从扩展抽象类的子类公开调用,而不能从抽象类本身调用。对不起,如果我在这里太简单了,但我确实一直在寻找几个小时的答案,甚至找不到关于该主题的任何讨论。
让我们考虑以下示例(cmets 中的解释)。我希望能够打电话给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...
对于如何实现所需行为,我也愿意接受任何替代方法。
【问题讨论】:
标签: php encapsulation abstraction php-7.4