Examples:
Interface example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | <?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 ; } } ?> |
Extendable Interfaces
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | <?php interface a { public function foo(); } interface b extends a { public function baz(Baz $baz ); } // This will work class c implements b { public function foo() { } public function baz(Baz $baz ) { } } // This will not work and result in a fatal error class d implements b { public function foo() { } public function baz(Foo $foo ) { } } ?> |
Multiple interface inheritance
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | <?php 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() { } } ?> |
Interfaces with constants
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <?php interface a { const b = 'Interface constant' ; } // Prints: Interface constant echo a::b; // This will however not work because it's not allowed to // override constants. class b implements a { const b = 'Class constant' ; } ?> |
Please login to continue.