I was wondering what is better or more accepted when coding in PHP. I was taught, in Java, that class methods to get and set variables should be prefixed with “get” and “set”. What I want to know, though, is should I use these prefixes on regular PHP functions.
For example, to retrieve a username from a session variable I would either have
getUsername()
or
username()
What are the advantages and best practices. I know that using “get” is more mnemonic but it’s rather redundant (especially for a personal project that I don’t expect to be having other people read) but for the sake of good practice I would like to get it right.
While I’m at it, what is the proper naming convention for variables? Underscore-separated or camel-case? I’ve looked around and I’ve seen a mix of both. WordPress tends to use underscores in their function names but a lot of other sites say camel-case is best.
I personally try to stay away from getters/setters. I prefer to use the magic methods so then I can do
$foo->myVarwithout needing to explicitly call a function (I think it makes the code more readable).With that said, there are circumstances where I use explicit getters and setters (Basically in situations where the result would be ambiguous using the variables directly. Like if I map the magic methods to an internal array and have other member variables that need accessing). In those circumstances, I use
$foo->getMyVar()as the function signature.IMHO,
$foo->myVar()makes sense if you know it’s a variable. But what happens if you see$foo->show(). Does that mean to perform the show action? Or does that mean get the current setting for the show variable?I always try to name all methods with something that identifies what they do.
$foo->var()doesn’t give any indication to what’s going on. But$foo->showVar()does (At least moreso).As for naming convention, it’s all about who you read. I prefer camel-case. But there’s nothing wrong with underscores. Pick one, and stick with it. Consistency is more important than the choice itself…