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?

0


source to share


3 answers


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

+4


source


Nop, only __set. Perhaps you can use inheritance to avoid rewriting it all over the place.



+2


source


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

0


source







All Articles