-1

PHP

I am using an class which extends an Abstract class, which in turn implements an interface. The class will need to have a constant, call it NAME, defined for every class that extends the Abstract class.

How can I force the class to define a constant "NAME"?

Abstract classes can have a constant called name, but the implementing class would not be forced to override it.

The interface can have a constant, but interfaces can not have their constants overridden.

Is there ant way to do what I am trying to do?

Thanks

  • You can't change a constant. You can, however, use a static function to return the value you want (which you can hint at in the interface or define as a function in the abstract class) called something like `getName()` which all the child classes will need to define (and use like this: `Child1::getName()`). – Tom Feb 14 '15 at 22:47

1 Answers1

0

I will make the abstract class take in the name as a parameter. The method is protected, so all extending classes will have to store the NAME parameter somehow, doesnt matter how though.

Still dont understand why you cant force classes extending an Abstract class or interface to have define a constant in the same way you can force them to define a function.

  • Why you can't force defining a constant? Because constants are not inherited by the instance - they are addressed statically. And everything static has a code smell, so you should avoid it. – Sven Feb 14 '15 at 23:27