Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to store class variables in PHP? [closed]

Tags:

variables

php

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?

like image 472
Philip Morton Avatar asked Feb 13 '09 15:02

Philip Morton


4 Answers

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.

class someThing {

    private $data = array();

    public function __get( $property )
    {
        if ( isset( $this->data[$property] ) )
        {
            return $this->data[$property];
        }
        return null;
    }

    public function __set( $property, $value )
    {
        $this->data[$property] = $value;
    }
}

Then, objects of this class can be used like an instance of stdClass, only none of the members you set are actually public

$o = new someThing()
$o->cow = 'moo';
$o->dog = 'woof';
// etc

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.

like image 58
Peter Bailey Avatar answered Oct 22 '22 20:10

Peter Bailey


If you're using private $data; you've just got an impenetrable blob of data there... Explicitly stating them will make your life much easier if you're figuring out how a class works.

Another consideration is if you use an IDE with autocomplete - that's not going to work with the 2nd method.

like image 26
Greg Avatar answered Oct 22 '22 19:10

Greg


If code is repetitive, arrays and (foreach) loops neaten things. You need to decide if the "animal" concept in your code is repetitive or not, or if the code needs to dig in to the uniqueness of each member.

If I have to repeat myself more than once, I loop.

like image 43
tkotitan Avatar answered Oct 22 '22 20:10

tkotitan


  • Use the first method when you know you need that variable.
  • Use the second method (an array collection of variables) when you have dynamic variable needs.

You can combine these 2 methods, so some variables are hardcoded into your class, while others are dynamic. The hardcoded variables will have preference compared with magic methods.

like image 42
OIS Avatar answered Oct 22 '22 20:10

OIS