存储PHP类属性的最佳方法是什么?

Bra*_*ayn 4 php oop design-patterns class

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

有一段时间以来,我一直在与同事讨论如何在PHP类中存储属性.

那么你认为应该使用哪一个.像这样的东西:

Class test{
    public $attr1;
    public $attr2;
    .............. 
    public function __construct(){
        $this->attr1 = val;  
        $this->attr1 = val;
        ...................   
    }
}
Run Code Online (Sandbox Code Playgroud)

与:

Class test{
    public $data;

    public function __construct(){
        $this->data['attr1'] = val;
        $this->data['attr2'] = val;
        ..........................       
    }
}
Run Code Online (Sandbox Code Playgroud)

当您拥有必须经常存储和检索的许多属性的对象时,这一点很重要.

在处理具有许多属性的对象时,同样重要的是,您是为每个属性使用getter和setter,还是使用一个方法来设置all和one方法来获取所有属性?

Chr*_*ris 9

版本1是更"经典"的做事方式.你的对象与你说的完全一样.

我不能说哪个严格"更好",但我可以说哪个更方便.

我已经使用第二个版本(通常用于CodeIgniter中的数据库模型,特别是在早期开发期间)与自定义PHP5 getter和setter方法结合使用,以允许您动态地重载类.即

<?php
    class foo{
        private $data = array();

        function __construct()
        {
            # code...
        }

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

        public function __set($member, $value) {
            // The ID of the dataset is read-only
            if ($member == "id") {
                return;
            }
            if (isset($this->data[$member])) {
                $this->data[$member] = $value;
            }
        }
    }

    $bar = new foo()
    $bar->propertyDoesntExist = "this is a test";
    echo $bar->propertyDoesntExist; //outputs "this is a test"
?>
Run Code Online (Sandbox Code Playgroud)


var*_*tec 5

当且仅当数据来自外部源(例如BD查询)时,我才使用第二个版本.在那种情况下,当然建议使用通用__get()/__set()访问$this->data.您还可以考虑实现IteratorAggregate接口返回new ArrayIterator($this->data).