-1

I am trying to make abstract method clear to me , so I wrote this code and test it. But when I run it the following error appear :

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

so where is the problem and why ?

<?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();
?>
Anasoft
  • 3
  • 8

3 Answers3

1

You cannot declare abstract function in a concrete class. Update your Book class to be abstract.

abstract class Book
{
     abstract public function ClassName();
}
vee
  • 38,255
  • 7
  • 74
  • 78
1

Class must also use abstract keyword

<?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";
    }
}
Basic Bridge
  • 1,881
  • 4
  • 25
  • 37
  • hmm , so what if i have to call a variable or a function from class Book ? if it became abstract i can't do that right ? – Anasoft Feb 03 '14 at 06:53
  • No, if you make a function ( `method` ) in `class Book` it will not become abstract. But it is good to declare all the function that you are going to use in `abstract` class and follow the contract – Basic Bridge Feb 03 '14 at 06:56
0

You class has to be abstract.

Change

class Book

to

abstract class Book

Also, you are calling the functions wrongly.

Replace

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

to

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

Putting it all together

<?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
Shankar Narayana Damodaran
  • 68,075
  • 43
  • 96
  • 126