When and why should I use public
, private
, and protected
functions and variables inside a class? What is the difference between them?
Examples:
// Public
public $variable;
public function doSomething() {
// ...
}
// Private
private $variable;
private function doSomething() {
// ...
}
// Protected
protected $variable;
protected function doSomething() {
// ...
}
You use:
public
scope to make that property/method available from anywhere, other classes and instances of the object.
private
scope when you want your property/method to be visible in its own class only.
protected
scope when you want to make your property/method visible in all classes that extend current class including the parent class.
If you don't use any visibility modifier, the property / method will be public.
More: (For comprehensive information)
protected
scope when you want to make your variable/function visible in all classes that extend current class AND its parent classes.@Shahid - I don't understand your point. Any class that extends class A also extend A's parent class, no?
@JDelage - Please see the link
http://www.php.net/manual/en/language.oop5.visibility.php#109324
@Growler Why bother using objects at all then?
@Growler, a more helpful answer would be that it is good to hide as much of the inner workings of an object as possible. That way it is less likely to break. If you make everything public, then another programmer might alter a variable which you don't want changed by anything other than the inner workings of your object.