Interfaces
As you know PHP4 supports inheritance using the “class foo extends parent” syntax. In PHP4 AND in PHP5 a class
can only extend one class so multiple inheritance is not supported. An interface is a class that does not
implement any methods it only defines the method names and the parameters the methods have. Classes can then
‘implement’ as many interfaces as needed indicating that the class will implement the methods defined in the
interface.
can only extend one class so multiple inheritance is not supported. An interface is a class that does not
implement any methods it only defines the method names and the parameters the methods have. Classes can then
‘implement’ as many interfaces as needed indicating that the class will implement the methods defined in the
interface.
Example 5: Interfaces
<?php
interface displayable {
function display();
}
interface
printable {
function doprint();
}
class
foo implements displayable,printable {
function display() {
// code
}
function
doprint() {
// code
}
}
?>
This is very useful to make your code easier to read and understand, reading the class declaration you will know
that the class implements the displayable and printable interfaces so the class must have a display() method and
the class must have a print() method, no matter how they are implemented you know you can call the methods by just
reading the class declaration.
that the class implements the displayable and printable interfaces so the class must have a display() method and
the class must have a print() method, no matter how they are implemented you know you can call the methods by just
reading the class declaration.
Abstract classes
An abstract class is a class that cannot be instantiated.
An abstract class can, as any normal superclass, define methods and variables.
Abstract classes can also define asbtract methods, methods that are not implemented in the abstract class
but must be implemented in derived classes.
An abstract class can, as any normal superclass, define methods and variables.
Abstract classes can also define asbtract methods, methods that are not implemented in the abstract class
but must be implemented in derived classes.
Example 6: Asbtract classes
<?php
abstract class foo {
protected $x;
abstract function
display();
function
setX($x) {
$this->x = $x;
}
}
class
foo2 extends foo {
function display() {
// Code
}
}
?>