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

html - Sizing a high-res image (~8MB) to display entirely in a small div (circular, diameter 100px) -

java - IntelliJ - No such instance method -

identifier - Is it possible for an html5 document to have two ids? -