(on Friday, 29 May 2009, 01:12 PM -0700):
> Probably more of a general coding debate, but...
>
> What's your opinion on the pros and cons of using get and set
> accessors? What's the Zend Framework strategy on this? Do you have a
> preference one way or the other?
>
> Any examples you can give that support your opinion would be great.
>
> Here's one article suggesting that "getter and setter methods are
> evil". It's written toward Java, but it seems like the debate easily
> applies to PHP / ZF.
> http://www.javaworld.com/javaworld/jw-09-2003/jw-0905-toolbox.html.
> Do you agree with what the author says?
Actually, many of the arguments he makes against them are valid for
Java, but invalid for PHP.
In the case of Java, you have strong typing, so in many cases getters
and setters are overkill; you can alter the type of a member simply by
changing its definition in the class. In PHP, since we have loose
typing, the only way to enforce typing is to restrict access to members
via getters and setters. Using getters and setters also future-proofs
your code in the event that you need to add some business logic
surrounding setting or retrieving a property value.
One place where this is especially important is for offering lazy
loading of objects. In many caes, ZF getters will check to see if an
object is registered, and, if not, register a default case with it. This
moves object instantiation to the last possible moment -- the moment
when it is first used. (Actually, I think this is a use case the author
supports.)
All of this said... when possible, and where it makes sense, I like to
use direct property access. You just have to test carefully to ensure
that common use cases will not break the functionality of the class.
--
Matthew Weier O'Phinney
Project Lead | matthew@zend.com
Zend Framework | http://framework.zend.com/
没有评论:
发表评论