gpt4 book ai didi

php - 抽象类方法声明

转载 作者:可可西里 更新时间:2023-11-01 13:10:56 25 4
gpt4 key购买 nike

我刚刚写了这样的代码:

<?php
class test
{
// Force Extending class to define this method
abstract protected function getValue();
abstract protected function prefixValue($prefix);

// Common method
public function printOut() {
print $this->getValue() . "\n";
}
}
class testabs extends test{

public function getValue()
{

}
public function prefixValue($f)
{

}
}
$obj = new testabs();
?>

当我运行这段代码时,我收到以下错误:

Fatal error: Class test contains 2 abstract methods and must therefore be declared abstract or implement the remaining methods (test::getValue, test::prefixValue) in C:\wamp64\www\study\abstract.php on line 12

我理解这个错误的第一部分。我将类测试更改为抽象,错误消失了,但我无法理解 部分。

最佳答案

如果您要添加抽象方法,那么您还需要将类设为抽象。这样,就无法实例化该类 - 只能实例化非抽象子类。

方法visibility (引用第二小节Method Visiblilty)在小类中是不一样的。根据您是否希望子类之外的代码调用这些方法,您可以在 test 类中声明具有可见性 public 的(抽象)方法,或者声明子类方法也具有可见性 protected

注意 Class Abstraction page 的第二段,这解释了这一点:

When inheriting from an abstract class, all methods marked abstract in the parent's class declaration must be defined by the child; additionally, these methods must be defined with the same (or a less restricted) visibility. For example, if the abstract method is defined as protected, the function implementation must be defined as either protected or public, but not private

<?php
abstract class test{
// Force Extending class to define this method
abstract protected function getValue();
abstract protected function prefixValue($prefix);

// Common method
public function printOut() {
print $this->getValue() . "\n";
}
}
class testabs extends test{

protected function getValue()
{

}
/**
* this method can be called from other methods with this class
* or sub-classes, but not called directly by code outside of this class
**/
protected function prefixValue($f)
{

}
}
$obj = new testabs();
// this method cannot be called here because its visibility is protected
$obj->prefixValues();// Fatal Error
?>

关于php - 抽象类方法声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39814112/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com