加入收藏 | 设为首页 | 会员中心 | 我要投稿 安卓应用网 (https://www.0791zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > PHP > 正文

php – 抽象类方法声明

发布时间:2020-05-25 08:52:39 所属栏目:PHP 来源:互联网
导读:我刚写了这样的代码: ?phpclass test{// Force Extending class to define this methodabstract protected function getValue();abstract protected function prefixValue($prefix);// Common methodpublic function

我刚写了这样的代码:

<?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:wamp64wwwstudyabstract.php on line 12

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

如果要添加抽象方法,那么您还需要使类抽象化.这样,该类无法实例化 – 只有非抽象子类才可以.

visibility(参见第二小节Method Visiblilty)在子类中不相同.根据您是否希望通过子类之外的代码调用方法,可以使类test中的(抽象)方法为public,或者使子类方法也受到保护.

请注意07002的第二段,其中解释了这一点:

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
?>

(编辑:安卓应用网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读