Reputation:
There's the extract function for generating local variables from an array:
extract(['a' => 10, 'b' => 20]) // $a = 10, $b = 20
What would be a clean solution like the extract()
function, but for class members? Obviously I can do something along the lines of:
class User {
private $user_id;
private $password;
private $email;
public function __construct($params) {
$this->user_id = isset($params['user_id']) ? $params['user_id'] : null;
$this->password = isset($params['password']) ? $params['password'] : null;
$this->email = isset($params['email']) ? $params['email'] : null;
}
}
Is there a cleaner way to do this?
Upvotes: 2
Views: 48
Reputation: 72226
The cleanest way to do it is to avoid arrays and extract()
altogether and pass the constructor individual arguments:
public function __construct($user_id, $password, $email)
{
// Add validation and default values for each member as needed
$this->user_id = $user_id;
$this->password = $password;
$this->email = $email;
}
This way, another programmer1 that reads the code understands from a glance what arguments the constructor expects and what is their meaning.
It also makes the code that uses the class more clear. Compare:
$user = new User($id, $_POST['password'], $_POST['email']);
with:
$user = new User($_POST);
In the first case you don't have to read the code of class User
to understand why it fails or produces unexpected results. A quick peek on the content of $_POST
is enough to know if the values passed to User::__construct()
are the ones it expects.
1 The "other programmer" could (and most of the times will) be you, several months later.
Upvotes: 0
Reputation: 78994
A simple solution that behaves like extract()
:
foreach($params as $key => $val) {
$this->$key = $val;
}
Upvotes: 4