Class Variables

Not for 'how-to' coding questions but PHP theory instead, this forum is here for those of us who wish to learn about design aspects of programming with PHP.

Moderator: General Moderators

Post Reply
Ree
Forum Regular
Posts: 592
Joined: Fri Jun 10, 2005 1:43 am
Location: LT

Class Variables

Post 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?
The Monkey
Forum Contributor
Posts: 168
Joined: Tue Mar 09, 2004 9:05 am
Location: Arkansas, USA

Post 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. :)
User avatar
nielsene
DevNet Resident
Posts: 1834
Joined: Fri Aug 16, 2002 8:57 am
Location: Watertown, MA

Post 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.
McGruff
DevNet Master
Posts: 2893
Joined: Thu Jan 30, 2003 8:26 pm
Location: Glasgow, Scotland

Post 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.
Post Reply