php - how to properly initialize a new class and pass a value to use for it's methods -


say have following class:

class item{     public $itemid;     public $itemattribute;      function __construct($itemid){         $this->itemid = $itemid;     }     public function getdata(){         $this->itemattribute = foo($itemid);     } } 

then i'm initiating new object code:

$item = new item($itemid); $item->getdata(); var_dump($item); 

basically trying do, define $itemid when initialize object, , when call $item->getdata, have perform function, using defined $itemid. first class , attempt writing oop scratch, bear me. problem $itemid isnt being passed foo function within getdata.

the approach seems right (except need use $this-> access property), but: flavour , have @ how getter , setter normaly used. getter should return something, while setter sets something. if need "something" internal, should use method, or in constructor, etc..

class item{     public $itemid;     public $itemattribute;      function __construct($itemid){         $this->itemid = $itemid;     }      public function getitemid(){         return $this->itemid;     }      //option 1:)      public function calculateattributevalue(){        $this->itemattribute = foo($this->itemid);     }      //option 2:)     public function calculateattributevalue($func){        $this->itemattribute = $func($this->itemid);     }      //option 3:) (lazy loading)     public function getitemattribute(){        if ($this->itemattribute == null){            $this->itemattribute = foo($this->itemid);        }         return $this->itemattribute;     }      //option 4 (eager loading)     function __construct($itemid){         $this->itemid = $itemid;         $this->itemattribute = foo($this->itemid);     }      public function getitemattribute(){        return $this->itemattribute;     } } 

however idea, either use eager or lazy loading. whenever need "call" function in order compute value, before getter return value, design becomes sensitive "calling functions in right order", bad large classes, , worse, if 1 calculation depends on calculation done prior...

bad usage:

$myclass = new item(5); $myclass->calulatea(); $myclass->calculateb(); $myclass->getb(); 

better:

$myclass = new item(5); //calculates , b $myclass->getb(); 

or

$myclass = new item(5); $myclass->geta(); //calculates a. $myclass->getb(); //calculates b , when required. 

Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -