Which is Best Approach for Setting OOP Properties?

Hi! I have years of experience writing procedural code with PHP, and am finally learning OOP in PHP. But I have a question about the best method to interact with an instantiated object for those of you with lots of OOP experience.

Many of the tutorials I’ve watched 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->setTitle("Title Name");
$obj->setContent("Blah blah blah");

$disp = $obj->getContent();

OPTION 2: Array & Getter

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

$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.

Please let me know what you think, thanks!


I guess that depends on what setParams does. If it just does $this->$key = $value, then for all practical purposes, your class attributes are public, and there isn’t much point to having a class in the first class.

Hi Jeff,

Well, it’s a work-in-progress right now, but, the setParams() method will first validate all the properties before storing them, and not all the properties will be public.

if you use setters and getters then none of the properties need to be public

Would it be better if they were all private and only settable and gettable via methods? This is essentially what I’m trying to figure out I guess. What is the best method?

Option 1 is better in most cases, especially if your setter methods actually handles validation internally. But in some circumstances you may not even need setter methods, if your objects are immutable you can just set the properties through constructor.

As a suggestion, I can recommend this book. It will help you out in your endeavors to learn OOP. It certainly helped me. :smile:

PHP Objects, Patterns and Practice


This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.