[PHP] When writing comments, when not writing

Sep 9, 2020 PHP how to write comments

What should the comment be?

Comments should be concise and accurate so that they are easy to read and understand. I understand that, but if I wrote it in all the processing The entire source becomes hard to read.

Comments also need to be organized.

Unnecessary comments and necessary comments

It is better not to write in the comments what you can see.

// Determine if you are human
if ($ object-> isHuman () === true) {
// Make the name Taro
$ name ='tarou';

When you can clearly understand the contents of processing with the help of method names and variable names, I don’t think you need to bother to comment. You can understand it by reading it.

I need a comment

** ・ Why this happens ・ What are you doing (what is this) ・ Do you misunderstand **

When I thought it was the code I saw for the first time, I try to write a comment if I’m likely to get caught in these three points.

Why this happens

// No password = Not applicable because not registered
if (empty ($ user-> password)) {
return false;

Why is this happening? Not because there is no password, it is not out of scope It may be important that it is not a regular registration. I put a comment in such a case.

This is something (what are you doing)

// Sum up all order amounts
$ total_amount = array_sum (array_column ($ orders-> toArray (),'amount'));

A combination of PHP functions and the helper functions of the framework, I put comments when it is difficult to understand what I am doing at first glance.

I’m new to programming about this, so my understanding of the source is low, It may be included. However, for maintenance etc., I do not know what kind of understanding will see this source in the future, so There is also a side just in case.

Don’t get me wrong

// Email to administrator (note that this is separate from billing administrator)
$ this-> sendMailToAdmin ($ from, $ subject, $ body);

In this case, the processing including billing is done, and the two destinations are complicated. I felt like that, so I put it in. Things that are likely to be mistaken, but should never be mistaken (That’s all), I try to put it in.

It’s a feeling that I’ve been doing the program for a year, so If you have any opinions, I would like to hear from you.