Plural or singular naming standards for sub-properties

747 views Asked by At

A fair amount is written regarding class naming convention but not as much for properties and variables.

The typical rule of thumb seems to be do what sounds right. The variable name for a single item should be singular such as $user. Arrays are often either plural such as $users or concatenated with an appropriate descriptor such as $userList.

Assuming the plural array convention is used, what should be used for the user's id, name, sex, age, etc? For instance, $userName or $usersName?

How should this apply to array index names? Often I will keep it generic as the array name implies what the index applies to such as $users=['id'=>123,'name'=>'bob'];, other times it needs to be more descriptive and should it be ['userId'=>123,'userName'=>'bob'] or ['usersId'=>123,'usersName'=>'bob']?

Should such exist, please include any references to any authoritative formal bodies that define these naming conventions.

1

There are 1 answers

0
Sambhaji Katrajkar On

If you have array of users then the array name should be $users. And the $users variable will contain array of $user.

For $user properties, it should be specific like id, name, sex, age. For example $id, $name, $age. Because these properties are for user so we don't need to give it name as $userid or $username etc.

So whenever you write any code, in future, anyone can get the idea of your code by only reading your variable name itself. Like:

foreach($users as $user) {
  $user->id;
  $user->name; 
}