PHPBuilder - Introduction to PHP5 Page 4



RSS Twitter
Articles Tricks And Hacks

Introduction to PHP5 - Page 4

by: Luis Argerich
|
April 11, 2003

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.
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.

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.
Example 6: Asbtract classes

<?php
abstract class foo {
  protected 
$x;

  abstract function 
display();

  function 
setX($x) {
    
$this->$x;
  }
}
 

class 
foo2 extends foo {
  function 
display() {
    
// Code
  
}
}
?>

« Previous Page
1
|
2
|
3
|
4
|
5
|
6
|
7
|
8
Next Page »

Comment and Contribute

Your comment has been submitted and is pending approval.

Author:
Luis Argerich

Comment:



Comment:

(Maximum characters: 1200). You have characters left.