-1

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

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();
?>
4

3 回答 3

1

您不能abstract在具体类中声明函数。将您的课程更新Book为抽象的。

abstract class Book
{
     abstract public function ClassName();
}
于 2014-02-03T06:49:04.087 回答
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";
    }
}
于 2014-02-03T06:49:33.690 回答
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
于 2014-02-03T06:50:38.280 回答