oop - check if setter is set PHP -


hi there way check if setter in class set?

i've tried is_object , isset without proper result.

example:

class fruitsmodel{      public $fruitid;      public function setfruitid($fruitid){         $this->fruitid = $fruitid;     }      public function displayfruit()     {         if(setter_fruit not set){throw new exception("fruitid missing!");}          echo $this->fruitid;      }  } 

a developer should know methods need implemented in class. assuming not, how force him implement them without checking existance of methods in other methods programatically?

that's interfaces come in handy , for. see interface contract defines methods class must implement.

so cleanest way tackle task implement interface.

fruitsmodelinterface.php

<?php  interface fruitsmodelinterface{      public function setfruitid($fruitid);  } 

fruitsmodel.php

<?php  class fruitsmodel implements fruitsmodelinterface{      protected $fruitid;      public function setfruitid($fruitid){         $this->fruitid = $fruitid;     }      public function displayfruit()     {         if(is_null($this->fruitid))             throw new fruitsmodelexception('fruit id missing!');         echo $this->fruitid;         // you'd better go calling method         // getfruit() though , return $this->fruitid instead of echoing         // it. it's not job ob fruitsmodel output     }  } 

really, that's magic. force fruitsmodelinterface implement setfruitid() method implementing proper interface. in displayfruit() check if property has been assigned.

i made property protected, can sure value set within class or it's children.

happy coding!


further reading


Comments

Popular posts from this blog

php - regexp cyrillic filename not matches -

c# - OpenXML hanging while writing elements -

sql - Select Query has unexpected multiple records (MS Access) -