php - 存储 PHP 类属性的最佳方式是什么?

标签 php design-patterns oop class

<分区>

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

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

那么你觉得应该用哪一个呢?像这样:

Class test{
    public $attr1;
    public $attr2;
    .............. 
    public function __construct(){
        $this->attr1 = val;  
        $this->attr1 = val;
        ...................   
    }
}

对比:

Class test{
    public $data;

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

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

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

最佳答案

版本 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"
?>

关于php - 存储 PHP 类属性的最佳方式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/806013/

相关文章:

c++ - 析构函数调用的次数比我预期的多

php - 如何在 Htaccess 中编写多个规则

javascript - php javascript中的多折线图

php - 从自定义商店页面上的 woocommerce 循环中删除类别

php - Azure Web 应用程序、PHP 7.4、OCI8(Oracle 即时客户端 12.2.0.1.0)

php - 在不使用反射的情况下获取类名减去命名空间

java - MVC在哪里保留对 Controller 的引用?

java - effective Java Item1 - 用于创建对象的静态工厂方法

Android MVP 实现

c++ - 这种情况有没有更好的办法[垂头丧气]