Abstract
Abstract and Interfaces are design to create a series of constrains. Here the class fails to proper implement interface methods.
abstract class myAdapter
{
private $id;
abstract function insert();
abstract function update();
public function save()
{
// ...
}
}
class PDO_myAdapter extends myAdapter{
public function __construct($dsn)
{
// ...
}
public function insertAdapter()
{
// wrong method name
// it should be insert()
}
public function update()
{
// ...
}
// Fatal error: Class PDO_myAdapter contains 1 abstract method ...
// myAdapter::insert()
}
Interface
Interfaces specifies an API that a class must implement. Interfaces contain no body. Here the class method save() is not compatible with the interface.
interface myAdapter
{
public function insert();
public function update();
public function save($name=null);
}
class PDO_Adapter implements myAdapter
{
public function insert()
{
// ...
}
public function update()
{
// ...
}
public function save($name)
{
// wrong
}
// Fatal error
// must be compatible with myAdapter::save($name = NULL)
}
Questions and answers
How do you declare abstract class?
- a) abstract class A{}
- b) class A {}
Can abstract classes declare public methods with body?
- a) yes
- b) no
Abstract classes cannot declare abstract methods with body?
- a) false
- b) true
How do you declare interface?
- a) interface class myAdapter {}
Can we have public methods with body in interfaces?
- a) no
- b) yes
Which statment is true?
- a) A class implements multiple interfaces and extend only one class
- b) A class implements and extends multiple interfaces and abstract classes