3

I would like to prevent a child class from redeclaring some parent's attributes. How can I do that?

EDIT: If my parent class has a "title" property, i don't want that children can (re)declare property with this name

1
  • That makes no sense. A children can always "redeclare" the property, however, it makes no difference. Probably that's why there are no "final" properties, you just don't need that kind of thing.
    – hakre
    Commented Jun 2, 2012 at 11:59

2 Answers 2

4

i'm not sure if this will work but you could try playing with the Reflection class and detect if any child has redeclared the property and then fire an exception or something

UPDATE:

check this links out:

http://www.php.net/manual/en/reflectionproperty.getdeclaringclass.php

and

http://www.php.net/manual/en/reflectionproperty.setaccessible.php

It should help

2
  • This is what i was thinking. But before to do that, i ask for a "final" keyword for variable class
    – TeChn4K
    Commented Apr 8, 2012 at 17:57
  • php doesn't have a final keyword for properties, only for methods Commented Apr 8, 2012 at 17:58
0

Define class variable as private.

private $_var = 'would not be changed by a child class';
6
  • 3
    private $_var = 'would not be changed by a child class, or even usable in child class'; Commented Apr 8, 2012 at 23:44
  • @EliasVanOotegem: as far as I understand - the task was to prevent from redeclaring. If there may be a need to read access - no problem to write a getter.
    – MFix
    Commented May 10, 2012 at 8:25
  • true, but see the update of my answer. Caution is advised, especially when using setters, or if the private variable is initialized in the parent class' constructor Commented May 10, 2012 at 9:01
  • agree on that.... however it would be programmers fault... it's almost like if programmer would edit the source code of parent class... as programmers we have to find a golden point between protection and sanity.
    – MFix
    Commented May 11, 2012 at 9:09
  • You're right, it would be the programmer's fault. But in most cases, there's no telling who will be maintaining your code down the rode, or who will be using your class, so documenting the code and writing less error prone code is something to take into account as much as possible, hence I'd still use const INVARIABLE and const INVARIABLE = parent::INVARIABLE. Still, you make a valid point saying it's the programmers responsibility to know what (s)he's doing, and to document the code Commented May 11, 2012 at 9:23

Not the answer you're looking for? Browse other questions tagged or ask your own question.