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

前端 未结 5 2430
旧巷少年郎
旧巷少年郎 2021-02-20 11:08

I currently have my PHP class variables set up like this:

class someThing {

    private $cat;
    private $dog;
    private $mouse;
    private $hamster;
    pr         


        
5条回答
  •  甜味超标
    2021-02-20 11:55

    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.

提交回复
热议问题