downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | my php.net 
search for in the  

<Class AbstractionOverloading>
Last updated: Thu, 26 Jun 2008

Object Interfaces

Object interfaces allow you to create code which specifies which methods a class must implement, without having to define how these methods are handled.

Interfaces are defined using the interface keyword, in the same way as a standard class, but without any of the methods having their contents defined.

All methods declared in an interface must be public, this is the nature of an interface.

implements

To implement an interface, the implements operator is used. All methods in the interface must be implemented within a class; failure to do so will result in a fatal error. Classes may implement more than one interface if desired by separating each interface with a comma.

Note: A class cannot implement two interfaces that share function names, since it would cause ambiguity.

Examples

Example #1 Interface example

<?php
// Declare the interface 'iTemplate'
interface iTemplate
{
  
public function setVariable($name, $var);
  
public function getHtml($template);
}

// Implement the interface
// This will work
class Template implements iTemplate
{
  
private $vars = array();
 
  
public function setVariable($name, $var)
   {
      
$this->vars[$name] = $var;
   }
 
  
public function getHtml($template)
   {
       foreach(
$this->vars as $name => $value) {
          
$template = str_replace('{' . $name . '}', $value, $template);
       }
 
       return
$template;
   }
}

// This will not work
// Fatal error: Class BadTemplate contains 1 abstract methods
// and must therefore be declared abstract (iTemplate::getHtml)
class BadTemplate implements iTemplate
{
  
private $vars = array();
 
  
public function setVariable($name, $var)
   {
      
$this->vars[$name] = $var;
   }
}

?>

See also the instanceof operator.



add a noteadd a note User Contributed Notes
Object Interfaces
There are no user contributed notes for this page.




<Class AbstractionOverloading>
Last updated: Thu, 26 Jun 2008
show source | credits | sitemap | contact | advertising | mirror sites
Copyright © 2001-2005 The PHP Group
All rights reserved.
This unofficial mirror is operated at: http://phpbuilder.com/
Last updated: Tue Nov 1 20:20:59 2005 EST
Columns / Articles | Tips / Quickies | News | News Linking and RSS Feeds | Shared Code Library
Mail Archives | Support / Discussion Forums | Get Started! Links | Contribute! | Docs