如何声明抽象类?

时间:2014-02-03 06:47:31

标签: php abstract-function

我试图让抽象方法清楚,所以我编写了这段代码并对其进行了测试。但是当我运行它时会出现以下错误:

Fatal error: Class Book contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (Book::ClassName) in C:\AppServ\www\index2.php on line 5

那么问题出在哪里?为什么?

<?php
  class Book
{
     abstract public function ClassName();
}

 class firstBook extends Book{
    public function ClassName()
    {
        echo "Called form class firstBook";
    }

}

 class secondBook extends Book{
    public function ClassName() 
    {
        echo "Called from class secondBook";
    }
}
$o = new firstBook();
$o2 = new secondBook();
$o->Classname();
$o2->Classname();
?>

3 个答案:

答案 0 :(得分:1)

您无法在具体类中声明abstract函数。将您的Book课程更新为摘要。

abstract class Book
{
     abstract public function ClassName();
}

答案 1 :(得分:1)

类还必须使用abstract关键字

<?php
  abstract  class Book
{
     abstract public function ClassName();
}

 class firstBook extends Book{
    public function ClassName()
    {
        echo "Called form class firstBook";
    }

}

 class secondBook extends Book{
    public function ClassName() 
    {
        echo "Called from class secondBook";
    }
}

答案 2 :(得分:0)

你的课必须是抽象的。

更改

class Book

abstract class Book

另外,你错误地调用了这些函数。

替换

$o->Classname;
$o2->Classname;

$o->ClassName();
$o2->ClassName();

全部放在一起

<?php
abstract class Book
{
    abstract public function ClassName();
}

class firstBook extends Book{
    public function ClassName()
    {
        echo "Called form class firstBook";
    }

}

class secondBook extends Book{
    public function ClassName()
    {
        echo "Called from class secondBook";
    }
}
$o = new firstBook;
$o2 = new secondBook;
$o->ClassName();
$o2->ClassName();
?>

<强> OUTPUT :

Called form class firstBookCalled from class secondBook