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.


I never said they can't have constants, my point was only methods seem to be required by the interfaces properties and constants don't seem to work as expected. Perhaps I should have been more clear when I said "only works for."

Written by chrisw

Accepted Answer

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.

This page was build to provide you fast access to the question and the direct accepted answer.
The content is written by members of the community.
It is licensed under cc-wiki