Bird
0
0

What will be the output of the following code?

medium📝 Predict Output Q4 of 15
PHP - Interfaces and Traits
What will be the output of the following code?
interface Colors {
  const RED = 'red';
}
class Paint implements Colors {
  public function getColor() {
    return self::RED;
  }
}
$paint = new Paint();
echo $paint->getColor();
Anull
Bred
CError: Undefined constant RED
Dself::RED
Step-by-Step Solution
Solution:
  1. Step 1: Understand constant inheritance in interfaces

    Constants declared in interfaces are inherited by implementing classes and accessible via self::.
  2. Step 2: Analyze getColor() method

    It returns self::RED, which refers to the interface constant 'red'. So echo prints 'red'.
  3. Final Answer:

    red -> Option B
  4. Quick Check:

    Interface constants accessible via self:: in implementing class [OK]
Quick Trick: Implementing classes inherit interface constants accessible via self:: [OK]
Common Mistakes:
  • Expecting error accessing interface constant via self::
  • Thinking constants are not inherited
  • Confusing constant name with string output

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes