Bird
0
0

Consider the following PHP code:

medium📝 Predict Output Q5 of 15
PHP - Classes and Objects
Consider the following PHP code:
class ParentClass {
  protected $name = 'Parent';
}
class ChildClass extends ParentClass {
  public function getName() {
    return $this->name;
  }
}
$child = new ChildClass();
echo $child->getName();

What will be the output?
AChildClass
BError: Cannot access protected property
CParent
Dnull
Step-by-Step Solution
Solution:
  1. Step 1: Understand protected property inheritance

    Protected properties are accessible in child classes, so $this->name in ChildClass works.
  2. Step 2: Check returned value

    The property $name is set to 'Parent' in ParentClass, so getName() returns 'Parent'.
  3. Final Answer:

    Parent -> Option C
  4. Quick Check:

    Protected accessible in subclass = Parent [OK]
Quick Trick: Protected allows subclass access [OK]
Common Mistakes:
  • Expecting error on protected access
  • Confusing property values
  • Assuming child class overrides property

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes