Adam Adam - 4 years ago 230
PHP Question

PHP: Public, Private, Protected

When and why should I use and what's the difference between, public, private and protected

inside a class?


// Public
public $variable;
public function doSomething(){

// Private
private $variable;
private function doSomething(){

// Protected
protected $variable;
protected function doSomething(){

Answer Source

You use:

  • public scope to make that variable/function available from anywhere, other classes and instances of the object.

  • private scope when you want your variable/function to be visible in its own class only.

  • protected scope when you want to make your variable/function visible in all classes that extend current class including the parent class.

More: (For comprehensive information)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download