NYCPHP Meetup

NYPHP.org

[nycphp-talk] Getter/setter best practices

Chris Snyder chsnyder at gmail.com
Tue Jan 12 14:49:13 EST 2010


On Tue, Jan 12, 2010 at 12:12 PM, Rob Marscher
<rmarscher at beaffinitive.com> wrote:
> On Jan 12, 2010, at 11:58 AM, Yitzchak Schaffer wrote:
>> What's BP for changing the values of protected properties within a class that also has public getter/setters?  e.g. in Foo::doSomething() below:
> ...
>>  protected function doSomething()
>>  {
>>    $new_value = $this->getNewValue();
>>
>>    $this->bar = $new_value;
>>
>>    // OR
>>
>>    $this->setBar( $new_value );
>>  }
>> }
>
> If you go through the effort to create getter/setter methods, you should always use them.  Otherwise, you lose the benefit of having them - which is that more logic can easily be placed in the getter and setter methods to do something more than simply assign/retrieve the variable.
>

Yeah, agreed.

Also, if you think in terms of interfaces, there are only methods, not
properties. It's a subtle thing (and most of us don't use interfaces
in php) but it's a great way to ensure that you can swap out the
underlying class later and not break anything.

If the new class implements the same interface, there has to be a
setBar() method, but there may not be a public or protected bar
property.



More information about the talk mailing list