A community in which webmasters can ask for help with topics such as PHP coding , MySQL , IT jobs, web design, IT security.
Current location:homephp forumphp talk in 2008 yearLocking class members in PHP - page 1
User InfoPosts
Locking class members in PHP#1
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?

posted date: 2008-12-23 15:31:00


Re: Locking class members in PHP#2
I had made out the solution of this problem. click to view my topic...

hope that hepls.

posted date: 2008-12-23 15:31:01


Re: Locking class members in PHP#3
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?

posted date: 2008-12-23 15:35:00


Re: Locking class members in PHP#4
Nop, only __set. Perhaps you can use inheritance to avoid rewriting it everywhere.

posted date: 2008-12-23 15:39:00


Re: Locking class members in PHP#5
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

posted date: 2008-12-23 15:54:00


Re: Locking class members in PHP#6
...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.

posted date: 2008-12-23 17:10:00


Re: Locking class members in PHP#7
It could affect serialization.

posted date: 2009-03-13 05:50:00


select page: « 1 »
Copyright ©2008-2017 www.momige.com, all rights reserved.