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.
<?php
class foo{
private $data = array();
function __construct()
{
# code...
}
public function __get($member) {
if (isset($this->data[$member])) {
return $this->data[$member];
}
}
public function __set($member, $value) {
// The ID of the dataset is read-only
if ($member == "id") {
return;
}
if (isset($this->data[$member])) {
$this->data[$member] = $value;
}
}
}
$bar = new foo()
$bar->propertyDoesntExist = "this is a test";
echo $bar->propertyDoesntExist; //outputs "this is a test"
?>
I'd use second version if and only if the data comes as a whole from external source (e.g. BD query). In that case of course it'll be recommendable to have generic __get()
/__set()
to access $this->data
. You might also consider implementing IteratorAggregate interface returning new ArrayIterator($this->data)
.
Unless there are really convincing arguments for either version (depnding on the context) I always chose the format the lets my ide/tools provide better information about the types, classes, relationships, ... and until now that's the first format.
There are other ways to access the data "array-like".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With