+1 Yacoby's general answer. As far as his hint about moving the logic into another method i like to do something like the following:
class MyClass
{
protected $_initialized = false;
public function construct($data = null)
{
if(null !== $data)
{
$this->init($data);
}
}
public function init(array $data)
{
foreach($data as $property => $value)
{
$method = "set$property";
if(method_exists($this, $method)
{
$this->$method($value);
}
$this->_initialized = true;
}
return $this;
}
public function isInitialized()
{
return $this->_initialized;
}
}
Now by simply adding a setMyPropertyMEthod to the class i can then set this property via __construct
or init
by simply passing in the data as an array like array('myProperty' => 'myValue')
. Further more i can easily test from outside logic if the object has been "initialized" with the isInitialized
method. Now another thing you can do is add a list of "required" properties that need to be set and filter to make sure those are set during initialization or construction. It also gives you an easy way to set a whole bunch of options at a given time by simply calling init
(or setOptions
if you prefer).