Bird
0
0

What will be the output of this PHP code?

medium📝 Predict Output Q4 of 15
PHP - Classes and Objects
What will be the output of this PHP code?
class Person {
  protected $name = 'Alice';
  public function getName() {
    return $this->name;
  }
}
$person = new Person();
echo $person->getName();
AError: Cannot access protected property
Bnull
CAlice
DFatal error: Undefined property
Step-by-Step Solution
Solution:
  1. Step 1: Understand property visibility and method access

    The property $name is protected, so it cannot be accessed directly outside the class, but the public method getName() can access it inside the class.
  2. Step 2: Analyze the method call and output

    Calling getName() returns the protected property value 'Alice', so echo outputs 'Alice'.
  3. Final Answer:

    Alice -> Option C
  4. Quick Check:

    Protected property accessed via public method = Alice [OK]
Quick Trick: Protected properties accessed inside class methods work fine [OK]
Common Mistakes:
  • Trying to access protected property directly
  • Expecting an error on method call
  • Confusing protected with private access

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes