duanlanzhi5509 2016-06-17 03:34
浏览 33
已采纳

在PHP OOP中获取/设置属性的最佳方法是什么

Many of the tutorials I've watched about PHP OOP use getter and setter methods to set invidivual properties and retrieve data from an object. But I'm wondering if the second approach of passing all properties in an array is okay and if not, why?

$obj = new MyClass();

OPTION 1: Setter & Getter

$obj->setKeyword("orange");
$obj->setTitle("Title Name");
$obj->setPage(4);
$obj->setContent("Blah blah blah");
$obj->setTemplate("template.tpl");

$disp = $obj->getContent();

OPTION 2: Array & Getter

$params = array('keyword' => "orange",
                'title' => "Title Name",
                'page' => 4,
                'content' => "Blah blah blah",
                'template' => "template.tpl"
        );

$obj->setParams($params);
$disp = $obj->getContent();

I'm leaning toward OPTION 2 for a script I'm writing because there are about two dozen properties that can potentially be set for the object, and I feel that maybe just sending them all in an array is the easiest way to do it. I also don't need to create a get and set method for every property, which I think would cut down on the amount of code I need to create for the class.

Is there anything wrong with Option 2? Is it better to use getter and setter methods as shown in Option 1? Thanks!

  • 写回答

3条回答 默认 最新

  • doulao2029 2016-06-17 03:40
    关注

    There is nothing wrong with your second approach.

    Both must be available in my opinion.

    Almost every collection implementation that I know offers at least one mass assignment method.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀