Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between public, private, and protected?

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() {   // ... } 
like image 502
Adam Halasz Avatar asked Dec 05 '10 22:12

Adam Halasz


People also ask

What is the difference between protected and public?

The difference between public and protected is that public can be accessed from outside class but protected cannot be accessed from outside class.

What is the difference between protected and private?

private - only available to be accessed within the class that defines them. protected - accessible in the class that defines them and in other classes which inherit from that class.

What's the difference between protected private and public variables?

Public variables, are variables that are visible to all classes. Private variables, are variables that are visible only to the class to which they belong. Protected variables, are variables that are visible only to the class to which they belong, and any subclasses.


1 Answers

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)

  • PHP Manual - Visibility
like image 195
Sarfraz Avatar answered Sep 20 '22 14:09

Sarfraz