Search code examples
phpoopobject-design

Can you force child classes to override constants?


Is it possible to require objects in PHP 5.3 to contain certain constants or properties? I read a bit on PHP's interface model and it seems it only works for abstract public methods so that's right out. So what i'm asking is if there is a way to have two objects Object A and Object B. If Object B wants to extend Object A it must contain a particular constant or variable. How would you design this type of architecture? Thanks.


Solution

  • http://php.net/manual/en/language.oop5.interfaces.php#language.oop5.interfaces.constants

    Its possible for interfaces to have constants. Interface constants works exactly like class constants except they cannot be overridden by a class/interface that inherits it.

    Interface constants cannot be overridden by inheriting classes. Class constants can be overridden, but are not required to be (even if declared in an abstract class). Abstract classes are designed to enforce interface, not implementation. Constants fall under implementation, while methods define the interface. Thus, while constants can be declared with a default value in an abstract class, it is up to the child to decide whether to use or redefine them, or not.

    Your best alternative is to use "getter" methods, e.g.:

    abstract class MyAbstract
    {
        abstract public function getPropertyA();
        abstract public function getPropertyB();
    }
    

    Now, any class using extend MyAbstract will be required to define getPropertyA() and getPropertyB(), which ensures the values will always be accessible.