Bird
0
0

Consider this PHP code:

hard📝 Application Q9 of 15
PHP - Classes and Objects
Consider this PHP code:
class ParentClass {
  protected $value = 10;
}
class ChildClass extends ParentClass {
  public function getValue() {
    return $this->value;
  }
}
$child = new ChildClass();
echo $child->getValue();

What will be the output and why?
AError: Cannot access protected property
B10, because protected properties are accessible in child classes
Cnull, because property is not public
DFatal error: Undefined property
Step-by-Step Solution
Solution:
  1. Step 1: Understand protected property inheritance

    Protected properties are accessible inside the class and any subclass.
  2. Step 2: Analyze method access in child class

    The child class method getValue() accesses $this->value, which is allowed for protected properties.
  3. Final Answer:

    10, because protected properties are accessible in child classes -> Option B
  4. Quick Check:

    Protected property access in subclass = 10 [OK]
Quick Trick: Protected properties are inherited and accessible in subclasses [OK]
Common Mistakes:
  • Expecting error on protected property access
  • Confusing protected with private
  • Assuming property is undefined

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes