tags:

views:

138

answers:

3

In PHP, if you define a class, and then instantiate an object of that class, it's possible to later arbitrarily add new members to that class. For example:

class foo {
    public $bar = 5;
}

$A = new foo;
$A->temp = 10;

However, I'd like the ability to make it impossible to add new members this way. Basically I want the class to ONLY have the members that are specified in its definition; if you try to set any other members, it fatally errors. The intent here is that I want to define a class as a very specific set of properties, and ensure that ONLY those properties exist in the class, so that the class contents are well-defined and cannot change later on (the values of each member can change, but not the members themselves).

I realize I can do this with the __set method, and simply have it fatal error if you try to set a member which doesn't already exist, but that's annoying to have to include in every class definition (although I could define each of my classes to extend a base class with that method, but that's also annoying). E.g.:

class foo {
    public $bar = 5;

    private function __set($var, $val) {
        trigger_error("Cannot dynamically add members to a class", E_USER_ERROR);
    }
}

Is there any other (preferably more convenient) way to do this? Aside from modifying PHP itself to disallow this behavior?

A: 

I have to ask why you need to do this? If a member is assigned and does not exist it does not affect the methods, and if it is private it will throw an error. So why do you need to do this, or did I completely misread the question?

Unkwntech
In narrow terms, I want to avoid the possibility of member typos. Imagine a class with a property named $char_lists, and then someone does $Object->chr_lists = array(1, 2, 3). It'd silently fail and be annoying to track down. Or, someone might add a new property and use it, but then...
dirtside
...other people modifying that code later don't understand where this mysterious variable comes from or what it's for, because it's not in the class definition. Classes should be exactly as defined in the class definition.
dirtside
It could affect serialization.
jmucchiello
+1  A: 

Nop, only __set. Perhaps you can use inheritance to avoid rewriting it everywhere.

Vilx-
+2  A: 

No. There's no better way than __set in a base class — yet. This is a known problem and is planned to be addressed in the future:

Introduce concept of “strict classes” that do not permit dynamic property creation

porneL