Bird
0
0

What will be the output of this PHP code?

medium📝 Predict Output Q5 of 15
PHP - Classes and Objects
What will be the output of this PHP code?
class Animal {
  private $type = 'Dog';
  public function getType() {
    return $this->type;
  }
}
$animal = new Animal();
echo $animal->type;
AError: Cannot access private property
Bnull
CDog
DFatal error: Undefined property
Step-by-Step Solution
Solution:
  1. Step 1: Identify property visibility and access

    The property $type is private, so it cannot be accessed directly outside the class.
  2. Step 2: Analyze the direct property access

    Accessing $animal->type directly causes an error because private properties are inaccessible outside the class.
  3. Final Answer:

    Error: Cannot access private property -> Option A
  4. Quick Check:

    Direct access to private property = error [OK]
Quick Trick: Private properties cannot be accessed directly outside the class [OK]
Common Mistakes:
  • Expecting private property to be accessible
  • Confusing private with protected
  • Trying to access via object directly

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes