Interfaces de Objetos

Interfaces de objetos permitem a criação de códigos que especificam quais métodos uma classe deve implementar, sem definir como esses métodos serão tratados.

Interfaces são definidas da mesma forma que classes, mas com a palavra-chave interface substituindo class e com nenhum dos métodos tendo seu conteúdo definido.

Todos os métodos declarados em uma interface devem ser públicos, essa é a natureza de uma interface.

implements

Para implementar uma interface, o operador implements é utilizado. Todos os métodos na interface devem ser implementados na classe; não fazê-lo resultará em um erro fatal. Classes podem implementar mais de uma interface se assim for desejado, separando cada interface com uma vírgula.

Nota:

Em versões anteriores ao PHP 5.3.9, uma classe não poderia implementar duas interfaces que especificassem um método com o mesmo nome, pois causaria ambiguidade. Versões mais recentes do PHP, isso é permitido, desde que os métodos duplicados tenham a mesma assinatura.

Nota:

Interfaces podem ser estendidas como as classes, usando o operador extends.

Nota:

A classe que implementa a interface precisa ter as mesmas assinaturas de método como definidas na interface. Não fazê-lo resultará em um erro fatal

Constantes

É possível ter constantes em interfaces. Constantes de interfaces funcionam exatamente como constantes de classes, com exceção de não poderem ser sobrescritas por uma classe/interface herdeira.

Exemplos

Exemplo #1 Exemplo de Interface

<?php

// Declara a interface 'iTemplate'
interface iTemplate
{
    public function 
setVariable($name$var);
    public function 
getHtml($template);
}

// Implementa a interface
// Isso funcionará
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;
    }
}

// Isso NÃO funcionará
// 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;
    }
}
?>

Exemplo #2 Interfaces estendíveis

<?php
interface a
{
    public function 
foo();
}

interface 
extends a
{
    public function 
baz(Baz $baz);
}

// Isto irá funcionar
class implements b
{
    public function 
foo()
    {
    }

    public function 
baz(Baz $baz)
    {
    }
}

// Isto não irá funcionar e resultará em um erro fatal
class implements b
{
    public function 
foo()
    {
    }

    public function 
baz(Foo $foo)
    {
    }
}
?>

Exemplo #3 Interface com herança múltipla

<?php
interface a
{
    public function 
foo();
}

interface 
b
{
    public function 
bar();
}

interface 
extends ab
{
    public function 
baz();
}

class 
implements c
{
    public function 
foo()
    {
    }

    public function 
bar()
    {
    }

    public function 
baz()
    {
    }
}
?>

Exemplo #4 Interfaces com constantes

<?php
interface a
{
    const 
'Interface constant';
}

// Imprime: Interface constant
echo a::b;


// Isto não funcionará porque não é permitido
// sobreescrever constantes.
class implements a
{
    const 
'Class constant';
}
?>

Uma interface, juntamente com a declaração de tipo, fornecem uma boa maneira de garantir que um objeto em particular possua determinados métodos. Veja o operador instanceof e declaração de tipo.

add a note add a note

User Contributed Notes 4 notes

up
17
thanhn2001 at gmail dot com
13 years ago
PHP prevents interface a contant to be overridden by a class/interface that DIRECTLY inherits it.  However, further inheritance allows it.  That means that interface constants are not final as mentioned in a previous comment.  Is this a bug or a feature?

<?php

interface a
{
    const
b = 'Interface constant';
}

// Prints: Interface constant
echo a::b;

class
b implements a
{
}

// This works!!!
class c extends b
{
    const
b = 'Class constant';
}

echo
c::b;
?>
up
2
williebegoode at att dot net
9 years ago
In their book on Design Patterns, Erich Gamma and his associates (AKA: "The Gang of Four") use the term "interface" and "abstract class" interchangeably. In working with PHP and design patterns, the interface, while clearly a "contract" of what to include in an implementation is also a helpful guide for both re-use and making changes. As long as the implemented changes follow the interface (whether it is an interface or abstract class with abstract methods), large complex programs can be safely updated without having to re-code an entire program or module.

In PHP coding with object interfaces (as a keyword) and "interfaces" in the more general context of use that includes both object interfaces and abstract classes, the purpose of "loose binding" (loosely bound objects) for ease of change and re-use is a helpful way to think about both uses of the  term "interface." The focus shifts from "contractual" to "loose binding" for the purpose of cooperative development and re-use.
up
0
Anonymous
2 years ago
Notice that in Example 5, public is written as pubic :)
up
0
xedin dot unknown at gmail dot com
3 years ago
This page says that if extending multiple interfaces with the same methods, the signature must be compatible. But this is not all there is to it: the order of `extends` matters. This is a known issue, and while it is disputable whether or not it is a bug, one should be aware of it, and code interfaces with this in mind.

https://bugs.php.net/bug.php?id=67270
https://bugs.php.net/bug.php?id=76361
https://bugs.php.net/bug.php?id=80785
To Top