Locking class members in PHP
In PHP, if you define a class and then instantiate an object of that class, it can then arbitrarily add new members to that class. For example:
class foo {
public $bar = 5;
}
$A = new foo;
$A->temp = 10;
However, I wish it was not possible to add new members. Basically, I want the class to ONLY have the members specified in its definition; if you try to install any other members, it will be a fatal mistake. The goal is that I want to define a class as a very specific set of properties and make sure that ONLY those properties exist in the class, so that the contents of the class are well-defined and cannot subsequently change (the values โโof each member can change, but not the participants themselves).
I realize I can do this with the __set method and just have its fatal error if you try to set a member that doesn't already exist, but it's annoying to include in every class definition (although I could define each of my classes extend base class by this method, but this is also annoying). For example:.
class foo {
public $bar = 5;
private function __set($var, $val) {
trigger_error("Cannot dynamically add members to a class", E_USER_ERROR);
}
}
Is there another (preferably more convenient) way to do this? Apart from changing PHP itself to disallow this behavior?
source to share
Not. There is no better way than __set
in the base class. This is a known issue and is planned to be addressed in the future :
Introduce the concept of "strong classes" that do not allow the creation of dynamic properties
source to share