I currently have my PHP class variables set up like this:
class someThing { private $cat; private $dog; private $mouse; private $hamster; private $zebra; private $lion; //getters, setters and other methods }
But I’ve also seen people using a single array to store all the variables:
class someThing { private $data = array(); //getters, setters and other methods }
Which do you use, and why? What are the advantages and disadvantages of each?
Generally, the first is better for reasons other people have stated here already.
However, if you need to store data on a class privately, but the footprint of data members is unknown, you’ll often see your 2nd example combined with __get() __set() hooks to hide that they’re being stored privately.
Then, objects of this class can be used like an instance of stdClass, only none of the members you set are actually public
This technique has its uses, but be aware that __get() and __set() are on the order of 10-12 times slower than setting public properties directly.