我试图让抽象方法清楚,所以我编写了这段代码并对其进行了测试。但是当我运行它时会出现以下错误:
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();
?>
答案 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