Key Takeaways
- Write self-explanatory code by using clear variable, function, and class names, type hinting, and assigning proper visibility to class methods. This will make the code understandable without the need for extensive comments.
- Strive for balance in commenting. While complex code blocks may need additional explanation, avoid over-commenting clear code or using comment blocks to compensate for poorly written code. Instead, refactor the code for clarity.
- Use doc block tags (@var, @param, @return, etc.) to provide information that cannot be included in the code itself, such as variable types or function return values. This information can be parsed by most IDEs and shown in hints.
- If detailed project documentation is necessary, include appropriate descriptions in doc blocks. However, if the code is easy to understand and doesn’t require extensive documentation, limit the tags to those providing information about variable types and return values.
Introduction
Pretty much every PHP developer writes comments along with the actual code. But the language itself doesn’t impose any rules on how to do so. You just have to wrap them around some specific tags and then you can write any content you want. So what exactly should be put in the comment blocks to keep them useful? Which parts of the code should be documented and which shouldn’t? In this article I will present some important rules which may help you in keeping your PHP code well documented and understandable.
1. Write code that explains itself
First and foremost, the code you write may serve as a good piece of documentation even without adding a single comment block to it. While transforming the logic into pieces of code you can do a lot to make the code clear. Here are just a few examples:
Variable, function and class naming
As you can name your pieces of code in almost any way you want, you can use it as your advantage in terms of keeping the code understandable. Just remember to choose clear names, not to make up any strange abbreviations or use names that may be ambiguous. If your variable represents an instance of a VeryImportantCustomer
class, just call it $veryImportantCustomer
, not $customer
, $vimpCust
or $tempcustomer
. Don’t be afraid of making typos in longer names as your IDE will probably warn you about unused variables or other inconsistencies in your code. I’m sure that using proper naming will help a lot in figuring out what’s going on in your code. It’s a simple rule but it may be easily forgotten in your everyday work.
Type hinting
PHP allows you to put class/interface names or array
/ callable
keywords next to a function parameter. It prevents you from making wrong function calls but it also serves as an important piece of information for anyone reading your code. You don’t have to examine the function body to get to know how to call the function. You can also quickly check how the different functions and classes can pass values between each other. And remember that your IDE will probably interpret the type hints and use them to describe the functions in popups or hints which are being displayed while you’re working.
Method visibility
Another concept worth mentioning is the method visibility. Assigning proper visibility to class methods is said to be an important part of writing quality object-oriented code. On one hand, it shows which code represents the part of the logic that should stay inside the class and shouldn’t be revealed to other classes in the application. On the other, it exposes certain class methods to public access so they can be called from outside the class and communicate with other parts of the application.
If you write code that includes setting proper method visibility, other developers will quickly figure out how to work with the class you’ve developed. They will see that there are a few public methods that they can refer to in their code. They will also notice which parts of the logic that you wrote are left to be handled by private class methods and probably shouldn’t be touched.
Again, such hints are also being interpreted by your IDE. The editor you use can probably show you a list of class methods, along with their visibility. Just look at the image below and notice the lock icons next to the method names:
2. Keep the balance
Of course you may feel that the code itself is not always clear enough and needs additional explanation. It is especially true when you’re implementing a complicated part of the business logic, performing complex calculations or just using commands that are difficult to understand at first sight (like regular expression patterns, array transformations etc.). In such cases writing a short comment will certainly help in getting to know what’s going on.
On the other hand, comment blocks shouldn’t make up for poorly written code. If your code contains too many loops or control structures and even you don’t know how it works without analyzing it for a couple of minutes, leaving it like that with a few comment lines isn’t the best solution. You should rather put some effort in refactoring the code instead of trying to explain it in comments.
Aside from complex code blocks, there are also such parts of code that are clear and do not represent any complicated logic. Some developers tend to put comment blocks even for these parts of their apps, which is unnecessary in my opinion. Let me show you an example:
<?php
class Deposit {
/**
* The deposit owner.
*
* @var string
*/
private $_owner;
/**
* The deposit amount.
*
* @var float
*/
private $_amount;
/**
* The date when the deposit was opened.
*
* @var DateTime
*/
private $_dateOpened;
/**
* Class constructor.
*
*/
public function __construct() {
//...
}
/**
* Sets the deposit owner.
*
* @param string $owner The deposit owner name.
*/
public function setOwner($owner) {
$this->_owner = $owner;
}
?>
Remember that the person who reads your code is usually a developer (or at least I suppose so), so he/she will be able to figure out that the _owner
property of the Deposit
class represents a deposit owner. That’s why I think that putting additional comments to such parts of the code can even make it less readable instead of helping the reader in any way.
Comments are often also unnecessary in other simple parts of your code, not only in class property definitions or typical methods (like constructors, getters or setters). Just see the example below:
<?php
public function showUserDetails() {
$userId = $this->Session->read('userId');
$userData = $this->getUserData($userId);
if(!$user->isActive()) {
throw new Exception("The user account hasn't been activated.");
}
//...
}
?>
I’m sure that you can easily figure out what’s going on in the part of the code presented above. But if you wanted to comment the code, it will probably look like this:
<?php
/**
* Shows the details of the user that is currently
* logged in.
*
*/
public function showUserDetails() {
//get the current user from session
$userId = $this->Session->read('userId');
//load the user data from database
$userData = $this->getUserData($userId);
//check if the user has an active account
if(!$user->isActive()) {
throw new Exception("The user account hasn't been activated.");
}
//...
}
?>
In fact, the comments added to the method contain almost the same words as those used in the code. Like we previously stated, proper naming makes your code understandable and easy to read. In my opinion, the method shown in the example above doesn’t need any additional comments as everything is described by the code itself. Of course, I still encourage you to write comments in those parts of your app that are more complex and need additional explanation.
3. Remember about the doc blocks
As you can see in the code examples above, some comment blocks contain specific keywords beginning with the @
character. I used @var
to describe the type of a class property and @param
to inform about the method parameter type. You can also use @return
tag which informs about the type of the value being returned by a function. Other tags may be employed to describe some general info about the application or its part (like the author, the package, the type of licence). You can read more about the doc blocks in the Introduction to PhpDoc article written by Moshe Teutsch.
Doc blocks tags contain information that cannot be included in the code itself. Specifying the type of class properties or function return values is especially helpful as it can be parsed by most of the IDEs and shown in hints. Of course you can also insert a custom text in a doc block which will serve as a function or class documentation. It may be especially important if your project needs to have its documentation available from outside the code. In such cases you can make use of the apps that analyze the doc blocks and generate the documentation of the whole application basing on their content. Read Bruno Skvorc’s Generate documentation with ApiGen article to find out more about such an approach.
If the code is easy to understand and I don’t need to produce an extended documentation, I just keep the tags that provide the information about the variable types and return values. In result, the code doesn’t get excessively complicated:
<?php
class Deposit {
/**
* @var string
*/
private $_owner;
/**
* @var float
*/
private $_amount;
/**
* @var DateTime
*/
private $_dateOpened;
//...
/**
* @param string $owner
*/
public function setOwner($owner) {
$this->_owner = $owner;
}
?>
Summary
In this article I presented some tips on how to maintain the code documentation in a PHP application. I think comments aren’t necessary if you produce code which is clear and just explains itself. The proper place to put comments is when you implement some complex logic or use commands that are just not very readable for a human. It is also worth remembering to insert doc block tags which describe variable types or function return values as such information cannot be included in the code itself. If you need to maintain more detailed project documentation, also put appropriate descriptions in doc blocks.
Feel free to put your comments about the points presented in the article or contact me through Google+. If you have a different opinion or use different rules in your work, tell us about it!
Frequently Asked Questions (FAQs) about PHP Code Documentation
What is the importance of documenting PHP code?
Documenting PHP code is crucial for several reasons. Firstly, it makes the code easier to understand for other developers who might work on your project in the future. This is particularly important in large projects where multiple developers are involved. Secondly, it serves as a form of in-line documentation that can be used to generate technical documentation automatically using tools like PHPDocumentor. Lastly, well-documented code is easier to debug and maintain, saving time and effort in the long run.
How can I use PHPDoc to document my PHP code?
PHPDoc is a popular tool used for generating API documentation from PHP source code. You can use PHPDoc by adding specially formatted comments above your classes, methods, and properties. These comments start with /** and end with */, and they can contain various tags that provide information about the code, such as @param, @return, and @throws.
What is the role of the @param tag in PHP documentation?
The @param tag is used in PHPDoc comments to specify the type and description of a function or method’s parameters. This helps other developers understand what kind of arguments they should pass to the function or method, and what each argument is used for.
How should I document PHP class methods?
When documenting PHP class methods, you should include a brief description of what the method does, the types and descriptions of its parameters (if any), and the type and description of its return value (if any). You can use PHPDoc tags like @param, @return, and @throws to provide this information.
What is the purpose of a leading underscore in PHP class methods?
A leading underscore in PHP class methods is often used to indicate that the method is intended to be private or protected, i.e., it should not be accessed directly from outside the class. However, this is just a convention and does not actually enforce any access restrictions.
How can I document comparison operators in PHP?
Comparison operators in PHP can be documented in the same way as other operators. You should explain what the operator does, what types of operands it can take, and what type of value it returns. You can also provide examples to illustrate its usage.
What is the best way to document PHP functions and classes inline?
The best way to document PHP functions and classes inline is to use PHPDoc comments. These comments should provide a brief description of the function or class, as well as information about its parameters, return value, and any exceptions it may throw. You can use PHPDoc tags like @param, @return, and @throws to provide this information.
How can I generate technical documentation from my PHP code?
You can generate technical documentation from your PHP code using tools like PHPDocumentor. These tools parse the PHPDoc comments in your code and generate HTML documentation that can be viewed in a web browser.
What is the role of the @return tag in PHP documentation?
The @return tag is used in PHPDoc comments to specify the type and description of a function or method’s return value. This helps other developers understand what kind of value they can expect the function or method to return.
How can I improve the readability of my PHP code?
There are several ways to improve the readability of your PHP code. One is to use meaningful names for your variables, functions, and classes. Another is to use comments to explain complex sections of code. You can also use whitespace and indentation to make your code easier to read. Lastly, you can follow a consistent coding style, such as the PSR-12 coding standard recommended by the PHP Framework Interop Group.
Jacek is a web developer specialized in building extensive web applications, mainly e-commerce solutions. The technologies he uses on a daily basis include PHP, MySQL, HTML+CSS and JS+jQuery. During the last few years he was the head developer of a highly customized online store platform in Poland. Now he's working on the development of several e-commerce websites running in Poland and Germany, often having hundreds of thousands pageviews a day. To take a break from coding, he does challenging crossfit workouts, goes out to taste some new food or dives into an interesting psychology magazine or book.