Bird
0
0

What will be the output of this PHP code?

medium📝 Predict Output Q5 of 15
PHP - Inheritance and Polymorphism
What will be the output of this PHP code?
class ParentClass {
    protected function greet() {
        return "Hello from Parent";
    }
}
class ChildClass extends ParentClass {
    public function greet() {
        return parent::greet() . " and Child";
    }
}
$child = new ChildClass();
echo $child->greet();
AHello from Parent
BHello from Parent and Child
CError: Cannot access protected method
DHello from Child
Step-by-Step Solution
Solution:
  1. Step 1: Understand protected method access in child

    Protected methods are accessible within child classes, so parent::greet() works.
  2. Step 2: Analyze the concatenation in child greet method

    The child method returns parent's greeting plus " and Child".
  3. Final Answer:

    Hello from Parent and Child -> Option B
  4. Quick Check:

    Protected method accessible in child = true [OK]
Quick Trick: Protected methods accessible in child classes [OK]
Common Mistakes:
  • Thinking protected methods are inaccessible
  • Expecting error on parent::greet() call
  • Ignoring string concatenation

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes