Junior — Middle
What do the access levels of elements in object-oriented programming mean, and what are the types?
sobes.tech AI
Answer from AI
In object-oriented programming (OOP), access levels determine which parts of a program can access certain class elements (properties and methods). In PHP, there are three main access levels:
- public — elements are accessible from anywhere, both inside and outside the class.
- protected — elements are accessible only within the class itself and its subclasses.
- private — elements are accessible only within the class where they are declared and are not accessible in subclasses or outside.
Example:
class Example {
public $publicVar = 'public';
protected $protectedVar = 'protected';
private $privateVar = 'private';
public function testAccess() {
echo $this->publicVar; // Accessible
echo $this->protectedVar; // Accessible
echo $this->privateVar; // Accessible
}
}
class ChildExample extends Example {
public function testAccess() {
echo $this->publicVar; // Accessible
echo $this->protectedVar; // Accessible
// echo $this->privateVar; // Error: not accessible
}
}
$obj = new Example();
echo $obj->publicVar; // Accessible
// echo $obj->protectedVar; // Error
// echo $obj->privateVar; // Error
Thus, access levels help encapsulate data and control its visibility.