benanamen Posted January 30, 2017 Share Posted January 30, 2017 Aside from setting a default value, is there any reason a class needs properties or a property with no default value? Here are two examples I am working with. One has a default car color from a property that gets changed (overwritten?), the other just sets the color with no property. Property with default color value <?php class Car { public $color = 'red'; } $bmw = new Car (); echo $bmw -> color; // red $bmw -> color = 'blue'; echo "<br>"; echo $bmw -> color; // blue Class with no property sets color <?php class Car { } $bmw = new Car (); $bmw -> color = 'blue'; echo $bmw -> color; // blue Quote Link to comment Share on other sites More sharing options...
requinix Posted January 30, 2017 Share Posted January 30, 2017 You should define properties, with or without defaults. Putting them in the class helps to document what the properties are, and personally I give defaults (even just 0 or empty strings) to be clear what type of values it will have. I mean, look at Car: class Car { public $color = 'red'; } class Car { public $color; } class Car { }The first has an obvious property, and the default may or may not make sense but at least you get a feel for it. (In this example I don't think having "red" makes sense.) The second has an obvious property but it's not clear whether it might have a string, int, or object as its value. (Docblocks are good for that too.) The third is completely unhelpful. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.