What's the best way to store PHP class attributes?


Question

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 ?

1
4
5/23/2017 11:46:49 AM

Accepted Answer

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"
?>
9
4/30/2009 9:36:41 AM

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).


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon