Recommended way to set a variable only once in PHP -
the use case follows: have variable $roles
need run db query set value. of methods in class need $roles
, don't need it, instantiate in constructor not option.
the question elegant way set value once methods need variable won't need check if value set , use right away.
i thought 2 options accomplish it, both of them don't feel natural.
option 1 (more procedural way):
class dosomething { public function getroles() { static $roles; if (!isset($roles)) { $roles = do_query_to_the_db_and_give_me_the_roles(); } return $roles; } public function dox() { $roles = $this->getroles(); } }
option 2: (more oop way)
class dosomething { private $roles; public function setroles() { $this->roles = do_query_to_the_db_and_give_me_the_roles(); } public function getroles() { if (!isset($this->roles)) { $this->setroles(); } return $this->roles; } public function dox() { $roles = $this->getroles(); } }
i'm more happy hear other approaches. thanks.
either way fine. if you're worried performance cache roles via memcache time period , refresh often.
Comments
Post a Comment