What is the difference between public, private, and protected?
Asked 07 September, 2021
Viewed 1.5K times
  • 52
Votes

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() {
  // ...
}

17 Answer