Hi Ashley, > -----Original Message----- > From: Ashley Sheridan [mailto:ash@xxxxxxxxxxxxxxxxxxxx] > Sent: Thursday, April 15, 2010 6:38 AM > To: PHP General List > Subject: class attributes and __construct > > I think this is probably going to end up as one of those coders' > preference type of things, but I was wondering what was considered the > general best approach. > > When creating a class, you can define default values for the object in > the class itself, and within the __construct function. Now, while I see > the advantage to using __construct to set properties that might depend > on a variable, what would be the best approach for any values that > might > likely remain at a default value and only ever change in a few rare > circumstances? > > For example: > > class Person > { > public $right_handed = true; I recommend setting it to private or protected instead of public to protect the integrity of the app. And add a get method/function to obtain the value. > function __construct($name, $height) > { > $this->name = $name; > $this-height = $height; > } > > function set_hand($side) > { > if($side == 'left' > { > $this->right_handed = false; > } > else > { > $this->right_handed = true; > } > } > > } > > Now, this is a simple example, but a value like $right_handed should > only ever change if it's not the typical. As most people are > right-handed it would make sense to set it to true and allow it to be > changed to false as necessary. What I'm wonder is, where is the best > place to set it to true, in the list of class properties at the top, or > in the __construct() function? > > I know I could move it to __construct and give it a default value in > the > arguments list, but that brings it's own problems. What if the argument > list grows too big, and which attribute would be deemed more important > than another that you might want to override it without specifying > every > other? Is there a rule of thumb as to what belongs in __construct and > what does not? > > Thanks, > Ash > http://www.ashleysheridan.co.uk > As for setting the default value in the construct, I recommend not to because should PHP support overloading later, you can then have another method/function to change its non-default value along with the initial parameters for the class. I use the constructor to set initial parameters for the class or initialize any class specific settings such as connection for DBAL. Regards, Tommy -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php