Interfaces provide a way of implementing multiple inheritance (not directly available in PHP) through the use of the keywords interface and implements.
Potentially, one could inherit from a parent class, and then inherit from that class and so in a chain like fashion. However, this would likely mean a number of the parents, parents, parents, etc, members might be included that might not be required, and avoids needing a very long trail like this:
class Test implements InterfaceA, InterfaceB, InterfaceC, InterfaceD, InterfaceE......InterfaceZ {}
Interfaces:
- 100% abstract classes
- Cannot be instantiated
- Contain just the method names, not their definitions (i.e. the inner guts of their code)
- Act like a contract to the class implementing the specified interface
- All method names within an interface have public visibility
- The implementing class must define the methods
The interface simply uses the keyword interface, which is then used by the class using the interface by way of the keyword implements:
<?php interface person { function setName($myName); function getName(); function setAge($myAge); function getAge(); } interface scientist{ function measure(); function writePaper(); } class Geek implements person, scientist { public $name; public $age; public function setName($myName){ $this->name = $myName; } public function getName(){ return $this->name ; } public function setAge($myAge){ $this->age = $myAge; } public function getAge(){ return $this->age ; } public function measure(){ echo "$this->name has just made a measurement!<br>"; } public function writePaper(){ echo "$this->name has written a paper!<br>"; } } $steve = new Geek(); $steve->setName("Stephen Hawking"); $steve->setAge(71); echo "The guy who invented big bangs: ". $steve->getName() . " is now " . $steve->getAge() . " years old!<br>"; $steve->measure(); $steve->writePaper(); echo "<pre>" . var_export($steve, TRUE) . "</pre>" ; ?>
Save & refresh browser:
The guy who invented big bangs: Stephen Hawking is now 71 years old! Stephen Hawking has just made a measurement! Stephen Hawking has written a paper!
Geek::__set_state(array( |