Page 1 of 1
Class Variables
Posted: Tue Aug 23, 2005 11:37 am
by Ree
When should a variable be declared as class property? I would think when it's used by more than one method of the class (including constructor). Is that right, or are there any other reasons?
Posted: Tue Aug 23, 2005 12:06 pm
by The Monkey
Also if you need to return the variable outside the class.
Unless you have PHP5, however, with the
__get() and __set() class methods, the best practice would probably be to return the variable via a method (result() or such). Then, later on, if you need to make sure that some action has occurred before something outside the class instance gets ahold of the variable, you can add the check to the result() method and not change any code outside the class.

Posted: Tue Aug 23, 2005 12:08 pm
by nielsene
When the variable is logically thought of as "part" of the class. When the variable is "controlled" by the class and not just "used" by the class.
Posted: Wed Aug 24, 2005 2:47 pm
by McGruff
As a rule I'd be looking to reduce scope as much as possible. Getting vars out of the global scope and into classes is the first step. Within a class, keep vars in the method scope unless they need to be class properties. "When it's used by more than one method" is a good answer.