I recently came across an article by Matthew Weier O'Phinney (ZF project lead) that contains sample code similar to this:
class User
{
protected $_data = array(
'username' => null,
'email' => null,
'fullname' => '',
'role' => 'guest',
);
/* ... */
}
Notice how what would traditionally be four different member variables is consolidated into one array. I can see the benefit of the clean constructor (only one parameter), but I doubt IDEs will be able to do auto-completion very well on the $_data
array.
One alternative I can think of is to use magic methods to have a constructor with a single parameter and the four members.
class User
{
protected $_username = null;
protected $_email = null;
protected $_fullname = '';
protected $_role = 'guest';
public function __construct($data)
{
foreach ($data as $key => $value) {
$this->$key = $value;
}
}
public function __set($name, $value) {
$member = "_$name";
$this->$member = $value;
}
}
The second block of code seems better...however I doubt I can write better code than Mr. O'Phinney. What is the best way to handle class members while still keeping a clean interface to the constructor?