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!

图片转代码服务由CSDN问答提供 功能建议

我观看的许多关于PHP OOP的教程都使用getter和setter方法设置invidivual属性并从中检索数据 一个东西。 但我想知道第二种传递数组中所有属性的方法是否可以,如果没有,为什么?

  $ obj = new MyClass(); 
   
 
 

选项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(  ); 
   
 
 

选项2:数组& Getter

  $ params = array('keyword'=>“orange”,
'title'=>“Title Name”,
'page'=&gt  ; 4,
'content'=>“Blah blah blah”,
'template'=>“template.tpl”
); 
 
 $ obj-> setParams($ params); \  n $ disp = $ obj-> getContent(); 
   
 
 

我倾向于选择2我正在编写的脚本因为大约有二十几个 可能为对象设置的属性,我觉得可能只是将它们全部发送到数组中是最简单的方法。 我也不需要为每个属性创建一个get和set方法,我认为这会减少我需要为类创建的代码量。

选项2有什么问题吗? 使用选项1中所示的getter和setter方法更好吗? 谢谢!

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

3条回答 默认 最新

相关推荐 更多相似问题