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?