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条)

报告相同问题?