Duplicate of: What's the best way to store class variables in PHP?
For some time I’ve been having this discussion with a co-worker on how should you store attributes within a PHP class.
So which one do you think it should be used. Something like this:
Class test{
public $attr1;
public $attr2;
..............
public function __construct(){
$this->attr1 = val;
$this->attr1 = val;
...................
}
}
Versus:
Class test{
public $data;
public function __construct(){
$this->data['attr1'] = val;
$this->data['attr2'] = val;
..........................
}
}
This is important when you have objects with many attributes that have to be stored and retrieved within often.
Also important when dealing with objects with many attributes, do you use getters and setters for each attribute or rather one method to set all and one method to get all ?
Version 1 is the more “classical” way of doing things. Your object is pretty much exactly as you say it is.
I can’t say which is strictly “better”, but I can say which I find more convenient.
I’ve used the second version (usually for database models in CodeIgniter, and particularly during early development) in combination with custom PHP5 getter and setter methods to allow you to overload the class dynamically. i.e.