在 PHP 中存储类变量的最佳方法是什么?

在 PHP 中存储类变量的最佳方法是什么?

问题描述:

我目前的 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?

一般来说,第一个更好,原因其他人已经在这里说明了.

Generally, the first is better for reasons other people have stated here already.

然而,如果你需要在一个类上私下存储数据,但数据成员的足迹是未知的,你会经常看到你的第二个例子结合了 __get() __set() 钩子来隐藏它们正在被存储私下.

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;
    }
}

那么,这个类的对象可以像stdClass的实例一样使用,只是你设置的成员实际上没有一个是公开的

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

此技术有其用途,但请注意,__get() 和 __set() 比直接设置公共属性慢 10-12 倍.

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.