0
0
PHPprogramming~10 mins

Access modifiers (public, private, protected) in PHP - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare a public property in the class.

PHP
<?php
class Car {
    [1] $color;
}
?>
Drag options to blanks, or click blank then click option'
Apublic
Bprivate
Cprotected
Dstatic
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'private' or 'protected' instead of 'public' for properties meant to be accessed outside.
2fill in blank
medium

Complete the code to declare a private method inside the class.

PHP
<?php
class User {
    [1] function setPassword($pass) {
        // code here
    }
}
?>
Drag options to blanks, or click blank then click option'
Afinal
Bpublic
Cprotected
Dprivate
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'public' or 'protected' when the method should be private.
3fill in blank
hard

Fix the error in the code by choosing the correct access modifier for the property.

PHP
<?php
class BankAccount {
    [1] $balance = 0;

    public function getBalance() {
        return $this->balance;
    }
}
?>
Drag options to blanks, or click blank then click option'
Apublic
Bprivate
Cprotected
Dvar
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'public' allows direct access which is unsafe for sensitive data.
4fill in blank
hard

Fill both blanks to declare a protected property and a public method to access it.

PHP
<?php
class Employee {
    [1] $salary;

    [2] function getSalary() {
        return $this->salary;
    }
}
?>
Drag options to blanks, or click blank then click option'
Aprotected
Bprivate
Cpublic
Dstatic
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'private' for the property when subclass access is needed.
Not making the method public to allow outside access.
5fill in blank
hard

Fill all three blanks to declare a private property, a protected method, and a public method.

PHP
<?php
class Document {
    [1] $content;

    [2] function editContent($newContent) {
        $this->content = $newContent;
    }

    [3] function readContent() {
        return $this->content;
    }
}
?>
Drag options to blanks, or click blank then click option'
Aprivate
Bprotected
Cpublic
Dfinal
Attempts:
3 left
💡 Hint
Common Mistakes
Using public for the property exposes it directly.
Making editContent public when it should be protected.