Bird
0
0

Identify the error in this PHP code:

medium📝 Debug Q14 of 15
PHP - Classes and Objects
Identify the error in this PHP code:
class ParentClass {
    protected $value = 10;
}

class ChildClass extends ParentClass {
    public function getValue() {
        return $this->value;
    }
}

$obj = new ParentClass();
echo $obj->value;
ASyntax error in class declaration
BChildClass cannot extend ParentClass
CCannot access protected property from outside the class
DNo error, outputs 10
Step-by-Step Solution
Solution:
  1. Step 1: Understand protected property access

    Protected properties can be accessed inside the class and child classes, but not from outside.
  2. Step 2: Check code usage

    The code tries to echo $obj->value where $obj is ParentClass instance, accessing protected property from outside, causing error.
  3. Final Answer:

    Cannot access protected property from outside the class -> Option C
  4. Quick Check:

    Protected outside class = error [OK]
Quick Trick: Protected properties not accessible outside class or children [OK]
Common Mistakes:
  • Trying to access protected property directly from object
  • Confusing protected with public
  • Assuming no error when accessing protected externally

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes