I think interfaces in php are most useful when it's about object identity
and controlling how certain objects should be handled.
Lets assume we have Apple and RawMeat objects which can be passed to FoodProcessor,
but FoodProcessor must cook RawMeat before consuming it.
Interfaces IN PHP are very useful in this kind of situations, but mostly they are pretty useless.PHP Code:interface IEatable{
function eatMe();
function vomitMe();
function cookMe();
}
class Food implements IEatable{
protected $done = 1;
function eatMe(){
if ($this->done){
echo 'Yumm.';
}else{
$this->vomitMe();
}
}
function vomitMe(){
echo 'Yaargh!';
}
function cookMe(){
$this->done = 1;
echo "I'm done!";
}
}
class Apple extends Food{}
interface IMustBeCooked{}
class RawMeat extends Food implements IMustBeCooked{
protected $done = 0;
}
class FoodProcessor{
function process($obj){
if ($obj instanceof IMustBeCooked){
$obj->cookMe();
}
if ($obj instanceof IEatable){
$obj->eatMe();
}
}
}
$obj = new FoodProcessor();
$obj->process(new Apple);
$obj->process(new RawMeat());








Bookmarks