Private, protected and public in php
Whether we're talking about class methods or class variables, this is rather crucial and people often tend to forget it or neglect its importance.
Private
These variables and methods are only accessible from the class in which they reside.
Protected
These variables and methods are accessible from the class in which they reside and from any subclass that is extending this class.
Public
These variables and methods are accessible from any script that includes the class.
Where do we go now?
You can browse through the recent articles or go to the archive for older items.
There are 4 comments for this article
Brian Reich on Dec 4, 2008
...and object properties defined in PHP 4 style (var $foo) are always public.
I also like to mark methods as "final" where applicable. You use final when a method should not be overridden in a subclass.
Jonas on Dec 4, 2008
Thanks for the addition. If we're talking about PHP4 anyway, it might also be worth mentioning that method declarations without access identifiers (private, public, protected) are always public.
Considering your remark on final methods, I'm not a big fan of declaring too much methods as final because I'd rather keep my classes as flexible as possible. If, at some point in time, I decide to extend a certain class, I would want to be able to do this without too much hassle. Nonetheless, I'm sure there are some situations where a method should be marked as final. I will keep an eye out for those situations when I run through my framework's classes in the future. There's always room for improvement ;)
Piccolo Principe on Dec 4, 2008
A note on private variables. "The class in which they reside" means methods of the current class, not of the current object. For instance this will work:
}
Gromitt on Dec 4, 2008
"Protected
These variables and methods are accessible from the class in which they reside and from any subclass that is extending this class."
Not only subclasses, but parent classes too (think about "template methods").