w3-tools.com - Free Webmaster Tools and Resources
 
w3-tools.com - Free Webmaster Tools and Resources
 Free Webmaster Tools and Resources

 



PHP Manual

This manual is provided as a courtesy. It is not an official source. Please check php.net for updated information.

PHP Manual

PHP Manual

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.

Examples

Example 19-17. 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.

Newsletter

Join to our newsletter and receive news and updates about our site.
Your name: 
E-mail address: 
Action: 
 

Hosted by

Search

Google
Web w3-tools.com

Links

  What is my IP? Find your IP address!     Valid XHTML 1.0 Transitional  
Copyright © 2006. by w3-tools.com. All rights reserved