I'm having a hard time trying to figure out a system of naming multi-dimensional PHP arrays, so that by looking at the variable name, you开发者_运维知识库 get a hint about the structure of the multi-dimensional array.
A fictional example:
$task = array('who'=>'John', 'what'=>'wash the dishes', 'priority'=>10);
$calendar[$year][$month][$day][$task_id] = $task;
In this case I named it "calendar" because the whole structure has a simple meaning as a whole, but in most cases there is no such direct connection to a single word or even a real-life concept. Also, I used date parts here (year, month, day) for exemplification, but normally my keys are integer database record ids.
So I would like a system of naming to describe this relation:
"year X month X day -> list of tasks"
more generally:
"key1 x key2 x key3 x ... x key n -> items"
A possible naming convention, using the word by and underscores as separators between keys:
$tasks_by_year_month_day = array(...); // items_by_key1_key2_key3
so that, keeping the same convention, I would write:
$tasks_by_month_day = $tasks_by_year_month_day['2010'];
or
$november2010Tasks_by_day = $tasks_by_year_month_day['2010']['nov'];
Is there a standard or cleaner way of naming this kind of arrays?
Thank you.
Having descriptive variable names when possible allows someone to understand the code more easily. However, there definitely comes the time when names become too long and the readability suffers.
Remember that the objective of variable names is to make the program easier to understand. If there is information about the data that isn't relevant, you shouldn't include it. For example:
function getTasksByDate($year, $month, $day) {
$tasks = getTasks();
return $tasks[$year][$month][$day];
}
In this case, who cares to rename $tasks
to $tasks_by_year_month_day
? It is more than clear what the indexing order is. Moreover, this example suggests the idea of an abstract data type.
With an abstract data type, you can expose greatly descriptive function names that operate on the task structure. This means that the only case where you really have to care about the order of indexing is in the functions which expose the ADT. At that point, you can comment the index order at the top of the file.
In short, you cannot hope to include every piece of information in your variable name. Most of the time no one wants every piece either. Try leveraging the current context to shorten your variable names and clarify your overall goal.
It's probably a personal/company decision. I often name them $lut_a_to_b
(lookup table for b by a). It helps to write comments with example structures for variables that live longer than a few lines.
精彩评论