Extendable class, protected property

I have a class which lists a few properties and methods, so far so good. The only thing relevant for this issue is the following snippet:

[php]class User {
private $explicitAttributes = array(“userid”, “username”, “password”);

// Rest of the properties and methods go here
}[/php]

the $explicitAttributes property lists a set of properties about the user that do not change throughout any execution path, so basically acts as a constant.

What I want, is for this class to have the following:

  • It needs to be extendable (works fine)
  • $explicitAttributes needs to remain inside the class scope (which it is through private/protected keyword), it’s not available outside the class
  • $explicitAttributes needs to be available read-only in this class (works fine) and in any subclasses (which it isn’t).

Declaring $explicitAttributes as private takes it away completely from any subclasses, but declaring it as protected gives full write access to any subclasses. That’s not good.

I cannot use the final keyword, as PHP5, unlike Java, only accepts it as a modifier for classes or methods (so not properties of classes). I cannot use the const either, since that would broaden the scope of the property beyond the class, which I’d like to avoid (no piece of code outside the class or its subclasses needs to have read access to $explicitAttributes, it is an internal constant, so to say).

Does anyone have ideas on how to get this to be done? I could of course declare a protected getter method, but that would be more of a workaround (and I don’t like workarounds - problems exist to be solved).

Thanks in advance,
Yours sincerely.

Perhaps using constants or define()… :-?

Nope, both const (as I pointed out) and define() broaden the scope of the variable, and I don’t want that. It has to remain internal.

oops, glanced over where you mentioned ‘I cannot use the const either…’

Been looking through the php manual (chm), and I cannot find anything that meets those requirements…
Perhaps this is a limitation in php?

Yea, I’m thinking it is. I was just wondering if anyone else had ever encountered this problem and knew of a way to solve it.

Sponsor our Newsletter | Privacy Policy | Terms of Service