Bird
0
0

Which code snippet correctly implements this?

hard📝 Application Q15 of 15
PHP - Interfaces and Traits
You want to define an interface Shape with constants CIRCLE = 1, SQUARE = 2, and TRIANGLE = 3. Then, create a class Circle implementing Shape that returns the shape type constant. Which code snippet correctly implements this?
Ainterface Shape { const CIRCLE = 1; const SQUARE = 2; const TRIANGLE = 3; } class Circle implements Shape { public function getType() { return Shape::CIRCLE; } }
Binterface Shape { public const CIRCLE = 1; public const SQUARE = 2; public const TRIANGLE = 3; } class Circle implements Shape { public function getType() { return $this->CIRCLE; } }
Cinterface Shape { const CIRCLE = 1; const SQUARE = 2; const TRIANGLE = 3; } class Circle implements Shape { public function getType() { return self::CIRCLE; } }
Dinterface Shape { const CIRCLE = 1; const SQUARE = 2; const TRIANGLE = 3; } class Circle implements Shape { public function getType() { return Shape->CIRCLE; } }
Step-by-Step Solution
Solution:
  1. Step 1: Define interface constants correctly

    Constants in interface Shape are declared using const without visibility modifiers.
  2. Step 2: Access constants correctly in implementing class

    Inside Circle, access the constant using Shape::CIRCLE. Using $this->CIRCLE or self::CIRCLE is incorrect because constants belong to the interface, not the class instance or class itself.
  3. Final Answer:

    Option A code snippet correctly implements interface constants and access -> Option A
  4. Quick Check:

    Interface constants accessed as InterfaceName::CONSTANT [OK]
Quick Trick: Access interface constants with InterfaceName::CONSTANT, not $this or self [OK]
Common Mistakes:
  • Adding public before const in interface
  • Using $this->CONSTANT to access interface constant
  • Using self::CONSTANT inside class for interface constant
  • Using arrow operator (->) with interface name

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes