Possible Duplicate:
interface vs abstract class
What are the advantage if i use abstract class in php?
What is the aim if i use abstract class or interfaces?
Both are simply creating defenition names with out body
What are the advantage if i use abstract class in php? i cant find anything good on that. I think i can easily do all work with out using the abstract class?
You could, naturally. However, if there are many objects that are of pretty much the same type, it might help to extract common functionality out into a "base" class, which means you don't have to duplicate that logic.
There are actually two reasons though. The first reason, for me, would be that all descendants of your abstract class have the same type, and both adhere to the exact same interface. That means that a PDF document for example will have the same interface as a docx document, and the client code doesn't have to care which object it's handling. Short example (in PHP).
<?php
abstract class Document {
protected $author;
public function __construct( $author ) {
$this->author = $author;
}
abstract public function render( );
public function author( ) {
return $this->author;
}
}
class PdfDocument extends Document {
public function render( ) {
// do something PDF specific here.
}
}
class DocxDocument extends Document {
public function render( ) {
// do something DOCX specific here.
}
}
class DocumentHandler {
public function handle( Document $document ) {
$this->log( 'Author has been read ' . $document->author( ) );
return $document->render( );
}
}
First of all; mind the fact that the DocumentHandler class has no knowledge of which type of Document it's actually handling. It doesn't even care. It's ignorant. However, it does know which methods can be called upon, because the interface between the two types of Documents are the same. This is called polymorphism, and could just as easily be achieved with the implementation of a Document interface.
The second part is; if each and every document has an author, and that author is always requested, you could copy the method over to the PdfDocument as well as the DocxDocument, but you'd be duplicating yourself. For instance, if you decide that you want the author to written with capitals, and you'd change return $this->author to ucwords( $this->author ), you'd have to do it as many times as you've copied that method. Using an abstract class, you can define behaviour, while marking the class itself as incomplete. This comes in very handy.