0
0
PHPprogramming~5 mins

Access modifiers (public, private, protected) in PHP - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the public access modifier mean in PHP?
The public access modifier means the property or method can be accessed from anywhere: inside the class, from subclasses, and from outside the class.
Click to reveal answer
beginner
What is the difference between private and protected access modifiers?
<strong>Private</strong> means the property or method can only be accessed inside the class where it is declared. <strong>Protected</strong> means it can be accessed inside the class and by subclasses (child classes), but not from outside.
Click to reveal answer
beginner
Show a simple PHP class with one public, one private, and one protected property.
<?php
class Example {
    public $name;
    private $age;
    protected $email;
}
?>
Click to reveal answer
beginner
Why do we use access modifiers in PHP classes?
Access modifiers help control who can see or change properties and methods. This protects data and helps organize code by hiding details that should not be accessed directly.
Click to reveal answer
beginner
Can a subclass access a private property of its parent class directly?
No, a subclass cannot access a private property of its parent class directly. Private properties are only accessible inside the class where they are declared.
Click to reveal answer
Which access modifier allows access from anywhere, including outside the class?
Apublic
Bprivate
Cprotected
Dstatic
Which access modifier restricts access only to the class where the property or method is declared?
Apublic
Bprivate
Cprotected
Dfinal
Can a protected property be accessed from a subclass?
AOnly if public
BNo
CYes
DOnly if static
What happens if you try to access a private property from outside its class?
AIt converts to public
BIt works normally
CIt returns null
DIt causes an error
Which access modifier is best to hide sensitive data inside a class?
Aprivate
Bpublic
Cprotected
Dglobal
Explain the differences between public, private, and protected access modifiers in PHP.
Think about who can see or use the property or method.
You got /3 concepts.
    Why is it important to use access modifiers when writing PHP classes?
    Consider how access modifiers help keep code safe and clear.
    You got /3 concepts.