I have a class ParentClass(), some child-classes ChildClass1(), ChildClass2(), etc. and an interface iChild(). The ChildClass() inherits from the ParentClass() and implements iChild():
class ChildClass1
extends ParentClass
implements iChild {}
class ChildClass2
extends ParentClass
implements iChild {}
In the iChild()-Interface, I would like to require, that some constants need to be filled (which are mainly identifiers and some functionality definitions). I have not found any meaning to do so, as constants may only be defined in the interface, but which are not redefinable in the implementing classes. The only workaround I found is to define some getter-functions in iChild(), which in turn return the necessary values, but that does not seem to be the right way to do. As I already extend from the ParentClass(), I also cannot use an abstract class to e.g. check the definition of the required constants in all ChildClasses.
Any ideas on how to tackle this problem?
Update: To answer a comment – with leaner and more readable I mean to following:
class ChildClass1 {
const MY_NAME = "Foo Bar Name 1";
}
-- vs --
class ChildClass1 {
public function GetMyName() {
return "Foo Bar Name 1";
}
}
I find the first example a lot more readable and understandable than the second. Unfortunatly, I currently do not have a way to enforce MY_NAME to be set by the ChildClasses.
I’m not sure that the proper solution here is for a constant. The very definition of a constant is that it does not change. If each implementation of
iChildneeds to define the constant it isn’t really a constant, it is a variable. I suggest adding in the appropriate getter methods, communicating to the user that they need to supply this information in their implementation.Ok, I did a little testing and it simply is not possible for a class to override a constant set by an interface it is implementing or a parent class it is extending. Class constants appear to be checked at compile time and a fatal error is thrown if you attempt to override it. For what you are trying to do the appropriate answer is providing getter methods in your interface.