+1 Yacoby的一般答案。至于他对逻辑移动到另一个方法暗示我喜欢做的事情如下所示:
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;
}
}
现在,通过简单地增加setMyPropertyMEthod到类,然后可以通过__construct
或init
只需通过设置该属性在数据中,像array('myProperty' => 'myValue')
这样的数组。进一步,我可以很容易地从外部逻辑测试,如果对象已经用isInitialized
方法“初始化”。现在你可以做的另一件事是添加一个需要设置的“必需”属性列表并进行筛选,以确保在初始化或构建过程中设置这些属性。它还为您提供了一种简单的方法,通过简单地拨打init
(或如果您愿意的话可以使用setOptions
),在给定时间设置一大堆选项。