Bird
0
0

Find the error in this PHP code:

medium📝 Debug Q6 of 15
PHP - Classes and Objects
Find the error in this PHP code:
<?php
class Animal {
  private $type;
  public function setType($type) {
    $this->type = $type;
  }
}
$animal = new Animal();
echo $animal->type;
?>
AClass name should be lowercase
BCannot access private property directly outside class
CMethod setType is not defined
DMissing semicolon after class definition
Step-by-Step Solution
Solution:
  1. Step 1: Identify property visibility

    The property 'type' is declared private, so it cannot be accessed directly outside the class.
  2. Step 2: Analyze the echo statement

    Trying to echo $animal->type causes an error because 'type' is private.
  3. Final Answer:

    Cannot access private property directly outside class -> Option B
  4. Quick Check:

    Private properties = no direct outside access [OK]
Quick Trick: Private properties need getters to access outside class [OK]
Common Mistakes:
  • Trying to access private properties directly
  • Ignoring visibility keywords
  • Assuming all properties are public by default

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes