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 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥30 求解达问题(有红包)