What is the difference between public, private, and protected?
In PHP, public
, private
, and protected
are access modifiers that control the visibility of class properties and methods.
public
properties and methods can be accessed from anywhere, inside or outside the class.private
properties and methods can only be accessed from within the class.protected
properties and methods can be accessed from within the class or from a subclass (a class that extends the original class).
Here's an example:
<?php
class MyClass
{
public $public_property = 'I am public';
private $private_property = 'I am private';
protected $protected_property = 'I am protected';
public function publicMethod()
{
// can access all properties and methods
}
private function privateMethod()
{
// can only access private properties and methods
}
protected function protectedMethod()
{
// can access protected properties and methods, as well as public properties and methods
}
}
$obj = new MyClass();
echo $obj->public_property; // outputs 'I am public'
echo $obj->private_property; // generates an error
echo $obj->protected_property; // generates an error
$obj->publicMethod(); // can be called
$obj->privateMethod(); // generates an error
$obj->protectedMethod(); // generates an error
Keep in mind that you cannot use private
or protected
access modifiers on properties or methods declared at the top level of a PHP script. They can only be used inside a class.