|
|
 |
Las interfaces de objetos permiten crear código el cual
especifica métodos que una clase debe implementar, sin
tener que definir como serán manejados esos métodos.
Las interfaces son definidas usando la palabra reservada 'interface',
de la misma manera que las clases estándar, pero sin que
cualquiera de los métodos tenga su contenido definido.
Todos los métodos en una interface deben ser publicos, esto es la
naturaleza de una interface.
Para implementar una interface, se usa el operador implements.
Todos los métodos en la interface deben ser implementados dentro
de una clase; de no hacerse asà resultará en error fatal.
Las clases pueden implementar más de una interface si se desea
al separar cada interface con una coma.
Ejemplo 19-17. Ejemplo de Interface |
<?php
interface iTemplate
{
public function setVariable($name, $var);
public function getHtml($template);
}
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;
}
}
class BadTemplate implements iTemplate
{
private $vars = array();
public function setVariable($name, $var)
{
$this->vars[$name] = $var;
}
}
?>
|
|
Vea tambien el operador instanceof.
add a note
User Contributed Notes
Interfaces de Objetos
vbolshov at rbc dot ru
10-Aug-2006 02:34
Consider the following:
[vbolshov@localhost tmp]$ cat t.php
<?php
error_reporting(E_ALL | E_STRICT);
interface i {
function f($arg);
}
class c implements i {
function f($arg, $arg2 = null)
{
}
}
?>
[vbolshov@localhost tmp]$ php t.php
[vbolshov@localhost tmp]$
PHP doesn't generate a Fatal Error in this case, although the method declaration in the class differs from that in the interface. This situation doesn't seem good to me: I'd prefer classes being strictly bound to their interfaces.
albert at friendly dot net
19-Jul-2006 08:53
Maybe this is a bit like cyrille.berliat's problem plus a somewhat solution.
Let's say we want to create a queue class (or a stack, or a double
linked list, the usual... :-).
Wouldn't it be nice if we could define a generic interface or abstract (base) class that dictates the way specific queues have to look like ?
Without having to specify the type of data to be queued.
But we _do_ want to be strict about the type of data to be passed to a specific queue type.
In other words: a bit of generic programming.
Alas, it seems that Type Hinting and Interface/abstract don't get along :(
But there might be a more runtime-involved solution. See below.
So, this won't work:
------
abstract class Object {} // as PHP(5) doesn't have a super-Object-base-class
class Cdata extends Object { } // i.e. Cdata IS-A Object
interface Iqueue {
public function enqueue(Object $data);
}
class Cmyqueue implements Iqueue {
public function enqueue(Cdata $data) { }
}
$q = new Cmyqueue;
$data = new Cdata;
$q->enqueue($data);
------
Nor will this 'compile':
------
abstract class Object {}
class Cdata extends Object {}
abstract class Iqueue extends Object {
abstract public function enqueue(Object $data);
}
class Cmyqueue extends Iqueue {
public function enqueue(Cdata $data) { }
}
$q = new Cmyqueue;
$data = new Cdata;
$q->enqueue($data);
---------
This however is possible:
abstract class Object {}
class Cdata extends Object
{
function __toString() { return('data'); }
}
abstract class Iqueue extends Object {
abstract public function enqueue(Object $data);
}
class Cmyqueue extends Iqueue {
public function enqueue(Object $data)
{ echo "enqueue '".$data->__toString()."'\n"; }
}
or:
interface Iqueue {
public function enqueue(Object $data);
}
class Cmyqueue implements Iqueue {
....
}
We could do our special Cmyqueue specific pre-processing before enqueu()ing.
But the compiler won't warn us if we pass anything other than the
object we expect to be passed.
We'd have to do something runtime like this:
class Cmyqueue extends Iqueue {
private function checkObjectType(Object &$obj)
{
if (get_class($obj) !== 'Cdata')
throw new Exception("You can only pass CData's to Cmyqueue");
}
public function enqueue(Object $data)
{
$this->checkObjectType($data);
echo "enqueue '".$data->__toString()."'\n";
}
}
hope this clears up some...
Grigori Kochanov
17-Jul-2006 02:24
The engine does not recognise the class that implements an interface as declared in the code written before the class declaration is placed.
This means that you can't place the declaration of a classes that implements an interfaces in the code beneath the creation of an instance.
Tony2001 said this is an expected behaviour of Zend engine.
Back to PHP 3 ;-)
<?php
var_dump(class_exists('validatorCheck'));
class validatorCheck implements ArrayAccess {
function offsetGet($key){}
function offsetSet($key, $value) {}
function offsetUnset($key) {}
function offsetExists($offset) {}
}
var_dump(class_exists('validatorCheck'));
?>
Result:
bool(false)
bool(true)
spiritus.canis at gmail dot com
25-Oct-2005 10:45
Regarding the example by cyrille.berliat:
This is not a problem and is consistent with other languages. You'd just want to use inheritance like so:
<?php
class AbstractClass {
public function __ToString ( ) { return 'Here I am'; }
}
class DescendantClass extends AbstractClass {}
interface MyInterface {
public function Hello ( AbstractClass $obj );
}
class MyClassOne implements MyInterface {
public function Hello ( AbstractClass $obj ) {
echo $obj;
}
} $myDC = new DescendantClass() ;
MyClassOne::Hello( $myDC ) ;
?>
cyrille.berliat[no spam]free.fr
17-Oct-2005 02:29
Interfaces and Type Hinting can be used but not with Inherintance in the same time :
<?
class AbstractClass
{
public function __ToString ( ) { return 'Here I\'m I'; }
}
class DescendantClass extends AbstractClass
{
}
interface MyI
{
public function Hello ( AbstractClass $obj );
}
class MyClassOne implements MyI
{
public function Hello ( AbstractClass $obj )
{
echo $obj;
}
} class MyClassTwo implements MyI
{
public function Hello ( DescendantClass $obj )
{
echo $obj;
}
} ?>
Something a little bit bad in PHP 5.0.4 :)
nuying117 at 163 dot com
13-Oct-2005 01:48
If a class implements two interfaces , but these two interfaces have a same method,for example
<?php
interface TestInterface1
{
function testMethod1();
function testMethod2();
}
interface TestInterface2
{
function testMethod2();
function testMethod3();
function testMethod4();
}
class ImplementClass implements TestInterface1,TestInterface2
{
function __construct()
{
echo "I am constructor\r\n";
}
function __destruct()
{
echo "I am destructor\r\n";
}
function testMethod1()
{}
function testMethod2()
{}
function testMethod3()
{}
function testMethod4()
{}
}
?>
It will cause a fatal error!
darealremco at msn dot com
02-Oct-2005 12:53
To two notes below: There is one situation where classes and interfaces can be used interchangeably. In function definitions you can define parameter types to be classes or interfaces. If this was not so then there would not be much use for interfaces at all.
warhog at warhog dot net
11-Aug-2005 08:35
on the post below:
An interface is in fact the same like an abstract class containing abstract methods, that's why interfaces share the same namespace as classes and why therefore "real" classes cannot have the same name as interfaces.
marcus at synchromedia dot co dot uk
28-Jul-2005 04:11
Classes and interface names share a common name space, so you can't have a class and an interface with the same name, even though the two can never be used ambiguously (i.e. there are no circumstances in which a class and an interface can be used interchangeably). e.g. this will not work:
interface foo {
public function bling();
}
class foo implements foo {
public function bling() {
}
}
You will get a 'Cannot redeclare class' error, even though it's only been declared as a class once.
tobias_demuth at web dot de
04-May-2005 02:21
The statement, that you have to implement _all_ methods of an interface has not to be taken that seriously, at least if you declare an abstract class and want to force the inheriting subclasses to implement the interface.
Just leave out all methods that should be implemented by the subclasses. But never write something like this:
<?php
interface Foo {
function bar();
}
abstract class FooBar implements Foo {
abstract function bar(); }
?>
This will end up with the following error-message:
Fatal error: Can't inherit abstract function Foo::bar() (previously declared abstract in FooBar) in path/to/file on line anylinenumber
erik dot zoltan at msn dot com
25-Feb-2005 10:43
When should you use interfaces? What are they good for?
Here are two examples.
1. Interfaces are an excellent way to implement reusability.
You can create a general interface for a number of situations
(such as a save to/load from disk interface.) You can then
implement the interface in a variety of different ways (e.g. for
formats such as tab delimited ASCII, XML and a database.)
You can write code that asks the object to "save itself to
disk" without having to worry what that means for the object
in question. One object might save itself to the database,
another to an XML and you can change this behavior over
time without having to rewrite the calling code.
This allows you to write reusable calling code that can work
for any number of different objects -- you don't need to know
what kind of object it is, as long as it obeys the common
interface.
2. Interfaces can also promote gradual evolution. On a
recent project I had some very complicated work to do and I
didn't know how to implement it. I could think of a "basic"
implementation but I knew I would have to change it later.
So I created interfaces in each of these cases, and created
at least one "basic" implementation of the interface that
was "good enough for now" even though I knew it would have
to change later.
When I came back to make the changes, I was able to create
some new implementations of these interfaces that added the
extra features I needed. Some of my classes still used
the "basic" implementations, but others needed the
specialized ones. I was able to add the new features to the
objects themselves without rewriting the calling code in most
cases. It was easy to evolve my code in this way because
the changes were mostly isolated -- they didn't spread all
over the place like you might expect.
mat.wilmots (at) wanadoo (dot) fr
20-Jan-2005 06:22
interfaces support multiple inheritance
<?php
interface SQL_Result extends SeekableIterator, Countable
{
}
abstract class SQL_Result_Common
{
}
class SQL_Result_mysql extends SQL_Result_Common implements SQL_Result
{
}
?>
This code raises a fatal error because SQL_Result_mysql doesn't implement the abstract methods of SeekableIterator (6) + Countable (1)
m.kurzyna AT nius waw pl
23-Dec-2004 06:04
You can have a class implementing two or more interfaces, just seperate them with a coma:
<?php
interface i_one {
public one();
}
interface i_two {
public two();
}
class oneANDtwo implements i_one, i_two {
public one() {}
public two() {}
}
?>
Of course all implemented interfaces will be tested, so one needs to have one() and two() in their class to avoid errors.
russ dot collier at gmail dot com
28-Nov-2004 10:24
You can also specify class constants in interfaces as well (similar to specifying 'public static final' fields in Java interfaces):
<?php
interface FooBar
{
const SOME_CONSTANT = 'I am an interface constant';
public function doStuff();
}
?>
Then you can access the constant by referring to the interface name, or an implementing class, (again similar to Java) e.g.:
<?php
class Baz implements FooBar
{
}
print Baz::SOME_CONSTANT;
print FooBar::SOME_CONSTANT;
?>
Both of the last print statements will output the same thing: the value of FooBar::SOME_CONSTANT
| |
| | Citas célebres | Cada noche le cuento a Dios mis preocupaciones. De todas formas, él va a estar despierto toda la noche. Mary C. Crowley Empresaria estadounidense (n. 1915) | | Citas en tu mail | | ©Contenidos Gratis |
| Chiste de... Varios | | Santos | - ¿Cuál es el santo más cuadrado?
- San Marcos.
- ¿Cuál es el santo de los bailarines?
- San Bailón.
- ¿Y el más deportista?
- San Gimnasio de Loyola.
- ¿Y el de los futbolistas?
- San Cadilla.
- ¿Y el santo más comido?
- San Güichito. | | Chistes en tu mail | | ©ContenidosGratis |
| Inicio | Acción | Estrategia | Palabras | Puzzles | Solitarios | Foro Trucos |  | Cake Mania Jugadores: 6835 Categoría del juego: Acción Objetivo del juego: Ayuda a Jill a recuperar la pastelería de su abuela llevando su propia pastelería; consigue clientes y gana dinero. |
|  | Rainbow Web Jugadores: 2199 Categoría del juego: Puzzles Objetivo del juego: Rompe un pegajoso hechizo y salva un reino de fantasía en Rainbow Web. Tendrás toneladas de diversión mientras juegas a este mágico desafío para la mente. |
|  | Mahjongg Fortuna Jugadores: 12462 Categoría del juego: Solitarios Objetivo del juego: Velocidad y habilidad mental son las armas más importantes en esta versión de un antiguo juego asiático. Despeja el tablero lo antes posible haciendo clic en las fichas iguales y gánate la fama eterna de la puntuación más alta. |
|  | Chainz 2 Jugadores: 6955 Categoría del juego: Puzzles Objetivo del juego: Entra en el mundo de las combinaciones con Chainz 2: Relinked, emocionante secuela del exitazo del año pasado, Chainz. Gira eslabones y crea combinaciones de 3 ó más. |
|  | Delicious Jugadores: 4405 Categoría del juego: Acción Objetivo del juego: ¿Eres un as de la multitarea? ¿Quieres que tus clientes estén contentos? ¡Pues Delicious es tu juego! Sacia el apetito de los clientes y tenlos contentos; ¡no te arriesgues! |
|  | Bookworm Jugadores: 4568 Categoría del juego: Palabras Objetivo del juego: Junta las letras para formar palabras. ¡Las palabras más largas valen más puntos! |
|  | Zuma Jugadores: 4976 Categoría del juego: Acción Objetivo del juego: Controla el ídolo de la rana de piedra de los antiguos Zuma en este intrigante enigma de acción. ¡Dispara bolas para formar conjuntos de tres, pero si dejas que lleguen a la calavera dorada morirás! |
|  | Jewel of Atlantis Jugadores: 3798 Categoría del juego: Puzzles Objetivo del juego: Descubre la ciudad hundida de la Atlántida y busca valiosos tesoros. Viaja más allá de las profundidades del mar y vive trepidantes aventuras en Jewel of Atlantis. |
|  | Jewel Quest Jugadores: 3727 Categoría del juego: Puzzles Objetivo del juego: Convierte la arena de la antigua selva en oro tan rápido como puedas juntando grupos de 3 elementos. ¡Los grupos más grandes valen más puntos! |
|  | Bejeweled 2 Jugadores: 3659 Categoría del juego: Puzzles Objetivo del juego: Con cuatro modos de juego únicos y fascinantes, nuevas piezas de juego explosivas e imponentes fondos planetarios, Bejeweled 2 es mucho más adictivo que nunca. |
|
|