Bird
0
0

Identify the error in this PHP code:

medium📝 Debug Q6 of 15
PHP - Classes and Objects
Identify the error in this PHP code:
class Animal {
    const TYPE = 'Mammal';
    public function getType() {
        return $this::TYPE;
    }
}
$animal = new Animal();
echo $animal->getType();
AError: Cannot use $this::TYPE, should use self::TYPE
BNo error, outputs 'Mammal'
CError: Constants cannot be accessed in methods
DError: Missing static keyword in method
Step-by-Step Solution
Solution:
  1. Step 1: Check constant access inside method

    Using $this::TYPE is valid to access class constants in PHP 7+.
  2. Step 2: Confirm output

    The method returns 'Mammal', so echo prints 'Mammal'.
  3. Final Answer:

    No error, outputs 'Mammal' -> Option B
  4. Quick Check:

    $this::CONST access inside method = valid [OK]
Quick Trick: You can use $this::CONST inside methods to access constants [OK]
Common Mistakes:
  • Thinking $this::CONST is invalid
  • Confusing constants with properties
  • Expecting static keyword needed

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes