What is the difference between a public, private, and protected property or method in PHP?
In PHP, the keywords “public”, “private”, and “protected” are used to specify the visibility of properties and methods within a class.
Here’s a brief explanation of the differences between them:
1) Public: A public property or method can be accessed from anywhere, both inside and outside the class. For example:
class MyClass {
public $publicProperty = 'public';public function publicMethod() {
return 'public';
}
}
$obj = new MyClass();
echo $obj->publicProperty; // Output: public
echo $obj->publicMethod(); // Output: public
2) Private: A private property or method can only be accessed from within the class where it is defined. It cannot be accessed from outside the class or from any of its child classes. For example:
class MyClass {
private $privateProperty = 'private';private function privateMethod() {
return 'private';
}
public function getPrivateProperty() {
return $this->privateProperty;
}
public function getPrivateMethod() {
return $this->privateMethod();
}
}
$obj = new MyClass();
echo $obj->getPrivateProperty(); // Output: private
echo $obj->getPrivateMethod(); // Output: private
echo $obj->privateProperty; // This will result in a fatal error
echo $obj->privateMethod(); // This will result in a fatal error
3) Protected: A protected property or method can only be accessed from within the class where it is defined or from its child classes. It cannot be accessed from outside the class hierarchy. For example:
class ParentClass {
protected $protectedProperty = 'protected';protected function protectedMethod() {
return 'protected';
}
}
class ChildClass extends ParentClass {
public function getProtectedProperty() {
return $this->protectedProperty;
}
public function getProtectedMethod() {
return $this->protectedMethod();
}
}
$obj = new ChildClass();
echo $obj->getProtectedProperty(); // Output: protected
echo $obj->getProtectedMethod(); // Output: protected
echo $obj->protectedProperty; // This will result in a fatal error
echo $obj->protectedMethod(); // This will result in a fatal error
In general, you should use “public” for properties and methods that need to be accessed from outside the class, “private” for properties and methods that are only used internally within the class, and “protected” for properties and methods that are used internally within the class hierarchy.