When To Declare Properties Of A Class?
I'm just getting into PHP OOP and I'm unclear on what properties I need to declare at the start of a class.
Do I declare properties:
A: that are arguments for methods?
B: are not arguments for methods but are still within a method?
C: that are returned from a method?
Edit For Example Here's an example userclass I'm trying to create
cl开发者_StackOverflow中文版ass user
{
public function selectMember($username,$password)
$query = "SELECT * FROM users WHERE username='$username' && password='$password'";
return $query;
}
So I would have to declare $query only at the top of the class?
The way I think of these things is that an object is a code representation of a real life object (duh). The car example above is a good one. For most real life objects there are attributes and actions. If our object is person, it will have attributes like name, height, weight, hair color. Then, our person will have actions, like run, sleep, eat.
The actions will be methods and the attributes will be properties. Properties will either be used in the actions or by other parts of the program which need to check the state of your object, IE, another part of your program asks the person how tall it is right now.
In most cases, return values and arguments will not be properties. A notable exception would be arguments you use to instantiate an object, as those will typically be needed by your other methods. As far as variables used within a method, these should be properties if they define the overall state of the object, but if you are creating a variable, like a counter, inside your method, that is just needed to accomplish the goal of the method, it doesn't make sense for it to be a property of your object.
I would start out by erring on the side of fewer properties. If you get to a point where you need a property to accomplish something, then create it. I wouldn't create them until I have a direct need. This way, you'll begin to get a feel for what properties an object will need in order to function logically.
I hope that makes a little sense.
Properties are pieces of data about the object. For example, to take the classic car example:
- The car's color, make/model, year, etc. are all properties of the car.
- There may be a method
StartCar
that requires aKey
object to start. The car does not have a key, therefore the key is not a property -- it is a method argument. But the car does have a lock that is capable of validating a given key. The argument and the property work together to perform the action (or, in this case, validate the action).
Each instance of the car class may have different values for these properties.
If you need specific help deciding what to make into properties, we will need more information about your specific requirements.
Php.net have a real good documentation about PHP OOP
It's pretty much your choice, according to the best answer in "When should I declare variables in a PHP class?".
精彩评论