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
Post a Comment