【问题标题】:Fatal error: Class xxx contains 1 abstract method and must therefore be declared abstract or implement the remaining methods [duplicate]致命错误:类 xxx 包含 1 个抽象方法,因此必须声明为抽象方法或实现其余方法 [重复]
【发布时间】:2017-05-28 16:48:19
【问题描述】:

我学 PHP 遇到问题:

<?php
class ProtectVis
{
    abstract protected function countMoney();
    protected $wage;

    protected function setHourly($hourly)
    {
        $money = $hourly;
        return $money;
    }
}

class ConcreteProtect extends ProtectVis
{
    function __construct()
    {
        $this->countMoney();
    }
    protected function countMoney()
    {
        echo "ok";
    }
}
$worker = new ConcreteProtect();

现在我有错误:

致命错误:ProtectVis 类包含 1 个抽象方法并且必须 因此被声明为抽象或实现其余方法 (ProtectVis::countMoney) 在

为什么?

【问题讨论】:

  • 你应该在ConcreteProtect类中定义一个名为countMoney的函数
  • 此函数已定义。
  • 您必须将ProtectVis 类声明为abstract,因为它包含abstract 方法。
  • “为什么?” -- 因为abstract classes 的 PHP 定义是这样说的。

标签: php


【解决方案1】:

根据 OOP 原则,每个包含至少一个抽象方法的类也被认为是抽象的。来自 PHP 手册:

定义为抽象的类不能被实例化,任何包含至少一个抽象方法的类也必须是抽象的。

所以你应该改变

class ProtectVis

abstract class ProtectVis

【讨论】:

    【解决方案2】:

    为 ProtectVis 声明抽象类,因为您使用的是抽象方法

    <?php
        abstract class ProtectVis
        {
            abstract protected function countMoney();
            protected $wage;
    
            protected function setHourly($hourly)
            {
                $money = $hourly;
                return $money;
            }
        }
    
        class ConcreteProtect extends ProtectVis
        {
            function __construct()
            {
                $this->countMoney();
            }
            protected function countMoney()
            {
                echo "ok";
            }
        }
    

    【讨论】:

      猜你喜欢
      • 2021-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-09
      • 2016-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多