在 PHP 中存储类变量的最佳方法是什么? [英] What's the best way to store class variables in PHP?

查看:32
本文介绍了在 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.

这篇关于在 PHP 中存储类变量的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆