If you have worked in object orient programming, you may have already know the keywords public, protected and private. These keywords are prefixed in class methods, properties or constants. If you are new to object oriented programming, you may probably wonder what these keywords are used for? How these keywords make functions, properties and constants different from each other.
In this article, we will describe what these keywords are used for and which one to use in defining any class method or properties.
These keywords are called visibility modifier. The visibility of property, constant or method can be defined prefixing keywords public, protected or private. If no visibility is defined to property, the property will be defined as public. Let's take examples in PHP language.
public
When you declare a method, constant or property as public, those methods, constants and properties can be accessed:
In the same class in which it is declared.
The classes which extends the same class.
Instances of the class.
Example:
<?php
class Vehicle {
public $year = '2020';
public function start() {
return 'ignition';
}
}
class Car extends Vehicle {
// we can access and redeclare public property and methods
public $year = '2021';
}
$honda = new Car();
echo($honda->year); // 2021
echo($honda->start()); // ignition
You can declare method, constant or property as public when you want to access those at anywhere.
protected
When you declare any method or property to private, those can be accessed:
In the same class.
The classes that inherit the above declared class.s
Example:
<?php
class Vehicle {
protected $year = '2020';
protected $color = 'red';
}
class Car extends Vehicle {
protected $color = 'blue'; // we can redeclare protected
public function getYear() {
return $this->year; // we can access variable here
}
public function getColor() {
return $this->color;
}
}
$honda = new Car();
echo($honda->getYear()); // 2020
echo($honda->getColor()); // blue
echo($honda->year); // Uncaught Error: Cannot access protected property Car::$year
So when you want to prevent any property or method to be access from the class object, then you may define them as protected.
private
When you declare any method or property as private, those can be accessed only in the same class. It can not even accessible in inherit class.
Example:
<?php
class Vehicle {
private $year = '2020';
public function getYear() {
return $this->year; // we can access private variable here
}
public function setYear($year) {
$this->year = $year;
}
}
$honda = new Vehicle();
echo($honda->getYear()); // 2020
echo($honda->setYear('2021')); // we can set private property using setter function
echo($honda->getYear()); // 2021
echo($honda->year); // Uncaught Error: Cannot access private property Vehicle::$year
So if you want to property or method to be declare private if can be used into the same class only. Generally helper function declare as private as it shouldn't be used outside class.