Junior — Middle
Can you name the main access modifiers and their features?
sobes.tech AI
Answer from AI
In PHP, there are three main access modifiers for class properties and methods:
public— accessible from anywhere, both inside and outside the class.protected— accessible within the class and its subclasses.private— accessible only within the class where it is declared.
Example:
class Example {
public $publicVar = 'Accessible everywhere';
protected $protectedVar = 'Accessible in class and subclasses';
private $privateVar = 'Accessible only in this class';
public function showVars() {
echo $this->publicVar . "\n";
echo $this->protectedVar . "\n";
echo $this->privateVar . "\n";
}
}
class ChildExample extends Example {
public function showProtected() {
echo $this->protectedVar; // Works
// echo $this->privateVar; // Error
}
}
Using access modifiers helps control encapsulation and protect internal object state.