// Объявим интерфейс 'iTemplate'
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;
}
}
// Это не будет работать
// Fatal error: Class BadTemplate contains 1 abstract methods
// and must therefore be declared abstract (iTemplate::getHtml)
// (Фатальная ошибка: Класс BadTemplate содержит 1 абстрактный метод
// и поэтому должнен быть объявлен абстрактным (iTemplate::getHtml))
class BadTemplate implements iTemplate
{
private $vars = array();
public function setVariable($name, $var)
{
$this->vars[$name] = $var;
}
}
Пример #2 Расширяемые интерфейсы
interface a
{
public function foo();
}
interface b extends a
{
public function baz(Baz $baz);
}
// Это сработает
class c implements b
{
public function foo()
{
}
public function baz(Baz $baz)
{
}
}
// Это не сработает и выдаст фатальную ошибку
class d implements b
{
public function foo()
{
}
public function baz(Foo $foo)
{
}
}
Пример #3 Множественное наследование интерфейсов
interface a
{
public function foo();
}
interface b
{
public function bar();
}
interface c extends a, b
{
public function baz();
}
class d implements c
{
public function foo()
{
}
public function bar()
{
}
public function baz()
{
}
}
Пример #4 Интерфейсы с константами
interface a
{
const b = 'Константа интерфейса';
}
// Выведет: Константа интерфейса
echo a::b;
// Вот это, однако, не будет работать, так как
// константы перекрывать нельзя.
class b implements a
{
const b = 'Class constant';
}
Интерфейс, совместно с контролем типов, предоставляет отличный способ проверки того, что определенный объект содержит определенный набор методов. Смотрите также оператор instanceof и контроль типов.
User Contributed Notes 38 notes
45
dlovell2001 at yahoo dot com ¶1 year ago
interface isStuffed {
public function getStuff($something=17);
}
class oof implements isStuffed {
public function getStuff($a=42) {
return $a;
}
}
$oof = new oof;
echo $oof->getStuff();
3
marasek AT telton POINT de ¶7 years ago
interface Comparable
{function compare(self $compare);}
7
mat.wilmots (at) wanadoo (dot) fr ¶8 years ago
interface SQL_Result extends SeekableIterator, Countable
{
// new stuff
}
abstract class SQL_Result_Common
{
// just because that's what one would do in reality, generic implementation
}
class SQL_Result_mysql extends SQL_Result_Common implements SQL_Result
{
// actual implementation
}
2
tobias_demuth at web dot de ¶8 years ago
interface Foo {
function bar();
}
abstract class FooBar implements Foo {
abstract function bar(); // just for making clear, that this
// method has to be implemented
}
4
drieick at hotmail dot com ¶3 years ago
interface Auxiliary_Platform {
public function Weapon();
public function Health();
public function Shields();
}
class T805 implements Auxiliary_Platform {
public function Weapon() {
var_dump(__CLASS__);
}
public function Health() {
var_dump(__CLASS__ . "::" . __FUNCTION__);
}
public function Shields() {
var_dump(__CLASS__ . "->" . __FUNCTION__);
}
}
class T806 extends T805 implements Auxiliary_Platform {
public function Weapon() {
var_dump(__CLASS__);
}
public function Shields() {
var_dump(__CLASS__ . "->" . __FUNCTION__);
}
}
$T805 = new T805();
$T805->Weapon();
$T805->Health();
$T805->Shields();
echo "<hr />";
$T806 = new T806();
$T806->Weapon();
$T806->Health();
$T806->Shields();
/* Output:
string(4) "T805"
string(12) "T805::Health"
string(13) "T805->Shields"
<hr />string(4) "T806"
string(12) "T805::Health"
string(13) "T806->Shields"
*/
1
Vladimir Kornea ¶5 months ago
#file : fruit/squeezable.php
namespace fruit
use Bar\Foo;
interface squeezable {
public function squeeze (Foo $foo);
}
1
thanhn2001 at gmail dot com ¶2 years ago
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;
0
tkostantinov ¶9 days ago
interface I
{
function foo(stdClass $arg);
}
class Test extends stdClass
{
}
class Implementation implements I
{
function foo(Test $arg)
{
}
}
0
Vladimir Kornea ¶4 months ago
$bar = new foo(); // Valid
class foo
{
}
0
Anonymous ¶3 years ago
interface IDoSomething {
public static function doSomething();
}
class One implements IDoSomething {
public static function doSomething() {
echo "One is doing something\n";
}
}
class Two extends One {
public static function doSomething() {
echo "Two is doing something\n";
}
}
function example(IDoSomething $doer) {
$doer::doSomething(); // "unexpected ::" in PHP 5.2
}
example(new One()); // One is doing something
example(new Two()); // Two is doing something
0
rskret at ranphilit dot com ¶4 years ago
# modify iface b...adding $num to get better understanding
interface b extends a
{
public function baz(Baz $baz,$num);
}
# mod claas c
class c implements b
{
public function foo()
{
echo'foo from class c';
}
public function baz(Baz $baz,$num)
{
var_dump ($baz);# object(Baz)#2 (1) { ["bb"]=> string(3) "hot" }
echo '<br />';
echo $baz->bb." $num";echo '<br />';# hot 6
}
}
# add a class Baz...
class Baz
{
public $bb='hot';
function ebaz(){
echo'this is BAZ';
}
}
# set instance of Baz and get some output...
$bazI=new Baz;
baz::ebaz();echo '<br />';# this is BAZ
c::baz($bazI,6);
0
cretz ¶5 years ago
interface ElectricalDevice{
public function power_on();
public function power_off();
}
interface FrequencyTuner{
public function get_frequencey();
public function set_frequency($f);
}
class ElectricFan implements ElectricalDevice{
// define ElectricalDevice...
}
class MicrowaveOven implements ElectricalDevice{
// define ElectricalDevice...
}
class StereoReceiver implements ElectricalDevice, FrequencyTuner{
// define ElectricalDevice...
// define FrequencyTuner...
}
class CellPhone implements ElectricalDevice, FrequencyTuner{
// define ElectricalDevice...
// define FrequencyTuner...
}
0
secure_admin ¶5 years ago
class Weather{
public $time, $temperature, $humidity;
public function __construct($tm, $t, $h){
$this->time = $tm;
$this->temperature = $t;
$this->humidity = $h;
}
public function __toString(){
return "Time: $this->time,
Temperature: $this->temperature°,
Humidity: $this->humidity%";
}
}
$forecasts = array(
new Weather("1:00 pm", 65, 42),
new Weather("2:00 pm", 66, 40),
new Weather("3:00 pm", 68, 39)
// add more weather reports as desired...
);
echo "Forecast for Chicago, IL:<br />";
foreach($forecasts as $forecast) echo ' - ' . $forecast '<br />';
0
mehea ¶5 years ago
interface water
{
public function makeItWet();
}
/**
* abstract class implements water but defines makeItWet
* in the most general way to allow child class to
* provide specificity
**/
abstract class weather implements water
{
private $cloudy;
public function makeItWet(){}
abstract public function start();
abstract public function getCloudy();
abstract public function setCloudy();
}
class rain extends weather {
private $cloudy;
public function start() {
return "Here's some weather. ";
}
public function makeItWet() {
return 'it is raining cats and dogs today.';
}
public function getCloudy() {
return $this->cloudy;
}
public function setCloudy($bln=false) {
$this->cloudy = $bln;
}
}
$a = new rain();
echo $a->start();
$a->setCloudy(true);
if ($a->getCloudy()) {
echo 'It is a cloudy day and ';
}
echo $a->makeItWet();
0
logik at centrum dot cz ¶5 years ago
interface water
{
public function makeItWet();
}
class weather
{
public function makeItWet()
{
return 'it may or may not be wet';
}
public function start()
{
return 'Here is some weather';
}
}
class rain extends weather implements water
{
public function makeItWet()
{
return 'It is wet';
}
}
class thunder extends weather implements water
{
}
$a = new rain();
echo $a->start() . "\n";
echo $a->makeItWet() . "\n";
$a = new thunder();
echo $a->start() . "\n";
echo $a->makeItWet() . "\n";
0
kaisershahid at gmail dot com ¶5 years ago
interface myInterface{
public function setStuff($id, $name);
}
class MyFirstClass implements myInterface{
public function setStuff($id, $name);
}
class MySecondClass implements myInterface{
public function setStuff($id, $name, $type);
}
class myThirdClass implements myInterface{
public function setStuff($id, $name, $type=0);
}
0
nrg1981 {AT} hotmail {DOT} com ¶6 years ago
interface water
{
public function makeItWet();
}
class weather
{
public function start()
{
return 'Here is some weather';
}
}
class rain extends weather implements water
{
public function makeItWet()
{
return 'It is wet';
}
}
$a = new rain();
echo $a->start();
echo $a->makeItWet();
0
Hayley Watson ¶6 years ago
interface isStuffable
{
public function getStuffed($ratio=0.5);
}
class Turkey implements isStuffable
{
public function getStuffed($stuffing=1)
{
// ....
}
}
0
zedd at fadingtwilight dot net ¶6 years ago
abstract class IFoo
{
abstract public function Foo();
}
abstract class IBar extends IFoo
{
// Fails; abstract method IFoo::Foo() must be defined in child and must match parent's definition
abstract public function Foo($bar);
}
0
Maikel ¶6 years ago
class MyChildClass extends MyParentClass implements MyInterface
{
// definition
}
0
Chris AT w3style DOT co.uk ¶7 years ago
interface Foo {
public function doFoo();
}
interface Bar extends Foo {
public function doBar();
}
class Zip implements Bar {
public function doFoo() {
echo "Foo";
}
public function doBar() {
echo "Bar";
}
}
$zip = new Zip();
$zip->doFoo();
$zip->doBar();
0
vbolshov at rbc dot ru ¶7 years ago
error_reporting(E_ALL | E_STRICT);
interface i {
function f($arg);
}
class c implements i {
function f($arg, $arg2 = null)
{
}
}
0
cyrille.berliat[no spam]free.fr ¶8 years ago
interface FooBar
{
const SOME_CONSTANT = 'I am an interface constant';
public function doStuff();
}
-1
spiritus.canis at gmail dot com ¶8 years ago
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;
}
} // Will work as Interface Satisfied
$myDC = new DescendantClass() ;
MyClassOne::Hello( $myDC ) ;
Описание на ru2.php.net
Описание на php.ru