• Awards Season
  • Big Stories
  • Pop Culture
  • Video Games
  • Celebrities

How to Find the Right Template to Write a Document for Free

Writing documents can be a daunting task, especially if you’re not sure where to start. Fortunately, there are many free templates available online that can help you get started. Here are some tips on how to find the right template to write a document for free.

Search Online

The first step in finding the right template is to search online. There are many websites that offer free document templates, so it’s important to take some time to browse through them and find one that best suits your needs. When searching, make sure to look for templates that are easy to use and have all the features you need.

Check Out Professional Templates

If you’re looking for a more professional-looking template, then it’s worth checking out some of the paid options available online. Professional templates often come with more features and customization options than free ones, so they can be worth the investment if you need something more polished and professional-looking.

Look for User Reviews

Finally, it’s always a good idea to read user reviews before downloading any template. This will help you get an idea of how well the template works and if there are any issues or problems with it. Reading user reviews can also give you an insight into how easy or difficult it is to use the template, which can be helpful when trying to decide which one is right for you.

Finding the right template to write a document for free doesn’t have to be difficult. By following these tips, you should be able to find one that meets your needs and helps you create a professional-looking document quickly and easily.

This text was generated using a large language model, and select text has been reviewed and moderated for purposes such as readability.

MORE FROM ASK.COM

how to write php documentation

Developer Resources

  • Accessibility Coding Standards
  • CSS Coding Standards
  • HTML Coding Standards
  • JavaScript Coding Standards
  • PHP Coding Standards
  • JavaScript Documentation Standards
  • PHP Documentation Standards
  • Markdown Style Guide

PHP Documentation Standards Edit

Miscellaneous, description, @since section (changelogs), other descriptions, line wrapping, 1.1 parameters that are arrays, 1.2 deprecated functions, 2.1 class members, 3. requires and includes, 4.1 duplicate hooks, 5.1 single line comments, 5.2 multi-line comments, 6. file headers, 7. constants, deprecated tags.

WordPress uses a customized documentation schema that draws inspiration from PHPDoc, an evolving standard for providing documentation to PHP code, which is maintained by phpDocumentor .

What Should Be Documented

PHP documentation in WordPress mostly takes the form of either formatted blocks of documentation or inline comments.

The following is a list of what should be documented in WordPress files:

  • Functions and class methods
  • Class members (including properties and constants)
  • Requires and includes
  • Hooks (actions and filters)
  • Inline comments
  • File headers

Top ↑

Documenting Tips

Summaries should be clear, simple, and brief. Avoid describing “why” an element exists, rather, focus on documenting “what” and “when” it does something.

A function, hook, class, or method is a third-person singular element, meaning that third-person singular verbs should be used to describe what each does.

Tip: Need help remembering how to conjugate for third-person singular verbs? Imagine prefixing the function, hook, class, or method summary with “It”:

  • Good : “(It) Does something.”
  • Bad : “(It) Do something.”

Summary examples:

  • Good: Displays the last modified date for a post.
  • Bad: Display the date on which the post was last modified.
  • Good: Filters the post content.
  • Bad: Lets you edit the post content that is output in the post template.
  • Good: _Fires after most of core is loaded, and the user is authenticated.
  • Bad: _Allows you to register custom post types, custom taxonomies, and other general housekeeping tasks after a lot of WordPress core has loaded.

Descriptive elements should be written as complete sentences. The one exception to this standard is file header summaries, which are intended as file “titles” more than sentences.

The serial (Oxford) comma should be used when listing elements in summaries, descriptions, and parameter or return descriptions.

@since : The recommended tool to use when searching for the version something was added to WordPress is svn blame . An additional resource for older hooks is the WordPress Hooks Database .

If the version number cannot be determined after using these tools, use @since Unknown .

Anything ported over from WPMU should use @since MU (3.0.0) . Existing @since MU (3.0.0) tags should not be changed.

Code Refactoring : It is permissible to space out the specific action or filter lines being documented to meet the coding standards, but do not refactor other code in the file.

Formatting Guidelines

Note: WordPress’ inline documentation standards for PHP are specifically tailored for optimum output on the official Code Reference . As such, following the standards in core and formatting as described below are extremely important to ensure expected output.

DocBlocks should directly precede the hook, action, function, method, or class line. There should not be any opening/closing tags or other things between the DocBlock and the declarations to prevent the parser becoming confused.

No HTML markup or Markdown of any kind should be used in the summary. If the text refers to an HTML element or tag, then it should be written as “image tag” or “img” element, not “ <img> “. For example:

  • Good: Fires when printing the link tag in the header.
  • Bad: Fires when printing the <link> tag in the header.

Inline PHPDoc tags may be used.

HTML markup should never be used outside of code examples, though Markdown can be used, as needed, in the description.

Use a hyphen (-) to create an unordered list, with a blank line before and after.

Use numbers to create an ordered list, with a blank line before and after.

  • Code samples would be created by indenting every line of the code by 4 spaces, with a blank line before and after. Blank lines in code samples also need to be indented by four spaces. Note that examples added in this way will be output in <pre> tags and not syntax-highlighted. * Description including a code sample: * * $status = array( * 'draft' => __( 'Draft' ), * 'pending' => __( 'Pending Review' ), * 'private' => __( 'Private' ), * 'publish' => __( 'Published' ) * ); * * The description continues on ...
  • Links in the form of URLs, such as related Trac tickets or other documentation, should be added in the appropriate place in the DocBlock using the @link tag: * Description text. * * @link https://core.trac.wordpress.org/ticket/20000

Every function, hook, class, and method should have a corresponding @since version associated with it (more on that below).

No HTML should be used in the descriptions for @since tags, though limited Markdown can be used as necessary, such as for adding backticks around variables, arguments, or parameter names, e.g. $variable .

Versions should be expressed in the 3-digit x.x.x style:

If significant changes have been made to a function, hook, class, or method, additional @since tags, versions, and descriptions should be added to provide a changelog for that function.

“Significant changes” include but are not limited to:

  • Adding new arguments or parameters.
  • Required arguments becoming optional.
  • Changing default/expected behaviors.
  • Functions or methods becoming wrappers for new APIs.
  • Parameters which have been renamed (once PHP 8.0 support has been announced).

PHPDoc supports multiple @since versions in DocBlocks for this explicit reason. When adding changelog entries to the @since block, a version should be cited, and a description should be added in sentence case and form and end with a period:

@param , @type , @return : No HTML should be used in the descriptions for these tags, though limited Markdown can be used as necessary, such as for adding backticks around variables, e.g. $variable .

  • Hooks, e.g. 'save_post'
  • Dynamic hooks, e.g. '$old_status_to_$new_status' (Note that any extra curly braces have been removed inside the quotes)
  • Default or available values should use single quotes, e.g. ‘draft’. Translatable strings should be identified as such in the description.
  • HTML elements and tags should be written as “audio element” or “link tag”.

DocBlock text should wrap to the next line after 80 characters of text. If the DocBlock itself is indented on the left 20 character positions, the wrap could occur at position 100, but should not extend beyond a total of 120 characters wide.

DocBlock Formatting

The examples provided in each section below show the expected DocBlock content and tags, as well as the exact formatting. Use spaces inside the DocBlock, not tabs, and ensure that items in each tag group are aligned according to the examples.

1. Functions & Class Methods

Functions and class methods should be formatted as follows:

  • Summary : A brief, one sentence explanation of the purpose of the function spanning a maximum of two lines. Use a period at the end.
  • Description : A supplement to the summary, providing a more detailed description. Use a period at the end of sentences.
  • @ignore : Used when an element is meant only for internal use and should be skipped from parsing.
  • @since x.x.x : Should always be 3-digit (e.g. @since 3.9.0 ). Exception is @since MU (3.0.0) .
  • @access : Only used for core-only functions or classes implementing “private” core APIs. If the element is private it will be output with a message stating its intention for internal use.
  • @see : Reference to a function, method, or class that is heavily-relied on within. See the note above about inline @see tags for expected formatting.
  • @link : URL that provides more information. This should never be used to reference another function, hook, class, or method, see @see .
  • @global : List PHP globals that are used within the function or method, with an optional description of the global. If multiple globals are listed, they should be aligned by type, variable, and description, with each other as a group.
  • @param : Note if the parameter is Optional before the description, and include a period at the end. The description should mention accepted values as well as the default. For example: Optional. This value does something. Accepts ‘post’, ‘term’, or empty. Default empty.
  • @return : Should contain all possible return types and a description for each. Use a period at the end. Note: @return void should not be used outside the default bundled themes and the PHP compatibility shims included in WordPress Core.

Parameters that are an array of arguments should be documented in the “originating” function only, and cross-referenced via an @see tag in corresponding DocBlocks.

Array values should be documented using WordPress’ flavor of hash notation style similar to how Hooks can be documented, each array value beginning with the @type tag, and taking the form of:

An example of an “originating” function and re-use of an argument array is wp_remote_request|post|get|head() .

In most cases, there is no need to mark individual arguments in a hash notation as optional , as the entire array is usually optional. Specifying “Optional.” in the hash notation description should suffice. In the case where the array is NOT optional, individual key/value pairs may be optional and should be marked as such as necessary.

If the function is deprecated and should not be used any longer, the @deprecated tag, along with the version and description of what to use instead, should be added. Note the additional use of an @see tag – the Code Reference uses this information to attempt to link to the replacement function.

Class DocBlocks should be formatted as follows:

  • Summary : A brief, one sentence explanation of the purpose of the class spanning a maximum of two lines. Use a period at the end.
  • Description : A supplement to the summary, providing a more detailed description. Use a period at the end.

If documenting a sub-class, it’s also helpful to include an @see tag reference to the super class:

2.1.1 Properties

Class properties should be formatted as follows:

  • Summary : Use a period at the end.
  • @var : Formatted the same way as @param , though the description may be omitted.

2.1.2 Constants

Files required or included should be documented with a summary description DocBlock. Optionally, this may apply to inline get_template_part() calls as needed for clarity.

4. Hooks (Actions and Filters)

Both action and filter hooks should be documented on the line immediately preceding the call to do_action() or do_action_ref_array() , or apply_filters() or apply_filters_ref_array() , and formatted as follows:

  • Summary : A brief, one line explanation of the purpose of the hook. Use a period at the end.
  • Description : A supplemental description to the summary, if warranted.
  • @ignore : Used when a hook is meant only for internal use and should be skipped from parsing.
  • @param : If the parameter is an array of arguments, document each argument using a hash notation (described above in the Parameters That Are Arrays section), and include a period at the end of each line.

Note that @return is not used for hook documentation, because action hooks return nothing, and filter hooks always return their first parameter.

If a hook is in the middle of a block of HTML or a long conditional, the DocBlock should be placed on the line immediately before the start of the HTML block or conditional, even if it means forcing line-breaks/PHP tags in a continuous line of HTML.

Tools to use when searching for the version a hook was added are svn blame , or the WordPress Hooks Database for older hooks. If, after using these tools, the version number cannot be determined, use @since Unknown .

Occasionally, hooks will be used multiple times in the same or separate core files. In these cases, rather than list the entire DocBlock every time, only the first-added or most logically-placed version of an action or filter will be fully documented. Subsequent versions should have a single-line comment.

For actions:

For filters:

To determine which instance should be documented, search for multiples of the same hook tag, then use svn blame to find the first use of the hook in terms of the earliest revision. If multiple instances of the hook were added in the same release, document the one most logically-placed as the “primary”.

5. Inline Comments

Inline comments inside methods and functions should be formatted as follows:

Important note : Multi-line comments must not begin with /** (double asterisk) as the parser might mistake it for a DocBlock. Use /* (single asterisk) instead.

The file header DocBlock is used to give an overview of what is contained in the file.

Whenever possible, all WordPress files should contain a header DocBlock, regardless of the file’s contents – this includes files containing classes.

The Summary section is meant to serve as a succinct description of what specific purpose the file serves.

  • Good: “Widgets API: WP_Widget class”
  • Bad: “Core widgets class”

The Description section can be used to better explain overview information for the file such as how the particular file fits into the overall makeup of an API or component.

  • Good: “The Widgets API is comprised of the WP_Widget and WP_Widget_Factory classes in addition to a variety of top-level functionality that implements the Widgets and related sidebar APIs. WordPress registers a number of common widgets by default.”

The constant DocBlock is used to give a description of the constant for better use and understanding.

Constants should be formatted as follows:

  • @var : Formatted the same way as @param . The description is optional.

PHPDoc Tags

Common PHPDoc tags used in WordPress include @since , @see , @global @param , and @return (see table below for full list).

For the most part, tags are used correctly, but not all the time. For instance, sometimes you’ll see an @link tag inline, linking to a separate function or method. “Linking” to known classes, methods, or functions is not necessary, as the Code Reference automatically links these elements. For “linking” hooks inline, the proper tag to use is @see – see the Other Descriptions section.

Note: PHPDoc tags work with some text editors/IDEs to display more information about a piece of code. It is useful to developers using those editors to understand what the purpose is, and where they would use it in their code. PhpStorm and Netbeans already support PHPDoc.

The following text editors/IDEs have extensions/bundles you can install that will help you auto-create DocBlocks:

  • Notepad++: DocIt for Notepad++ (Windows)
  • TextMate: php.tmbundle (Mac)
  • SublimeText: sublime packages (Windows, Mac, Linux)

Note: Even with help generating DocBlocks, most code editors don’t do a very thorough job – it’s likely you’ll need to manually fill in certain areas of any generated DocBlocks.

Preface: For the time being, and for the sake of consistency, WordPress Core will continue to use @subpackage tags – both when writing new DocBlocks, and editing old ones. Only when the new – external – PSR-5 recommendations are finalized, will across-the-board changes be considered, such as deprecating certain tags.

As proposed in the new PSR-5 recommendations, the following PHPDoc tag should be deprecated:

  • @subpackage (in favor of a unified package tag: @package Package\Subpackage )
  • @static (no longer needed)
  • @staticvar (no longer needed)

@package Tag in Plugins and Themes (bundled themes excluded)

Third-party plugin and theme authors must not use @package WordPress in their plugins or themes. The @package name for plugins should be the plugin name; for themes, it should be the theme name, spaced with underscores: Twenty_Fifteen .

@author Tag

It is WordPress’ policy not to use the @author tag, except in the case of maintaining it in external libraries. We do not want to imply any sort of “ownership” over code that might discourage contribution.

@copyright and @license Tags

The @copyright and @license tags are used in external libraries and scripts, and should not be used in WordPress core files.

  • @copyright is used to specify external script copyrights.
  • @license is used to specify external script licenses.
  • Wikipedia on PHPDoc
  • PEAR Standards
  • phpDocumentor
  • phpDocumentor Tutorial Tags
  • Draft PSR-5 recommendations
  • Draft PSR-19 recommendations

Code Commenting And PHP Documentation Generation

August 11, 2015 Code Commenting And PHP Documentation Generation Written by Artem

Code commenting and PHP documentation generation

Why do we need comments in code? How to write them? Where they are necessary and where they are not? How to comment code correctly? How to create the same documentation style for all members of the team? What are the tools for documentation generation? I will try to answer all the questions and share with you my ideas about this question.

So, there are two types of program documentation. The first type is to write comment in the code itself. The second variant is when the third party tool or repository is used, for example WIKI-engine, where the principles of application operation, the usage examples, the interaction modules are described, it is also provided with flowcharts and diagrams, generally speaking everything that you can’t write in code.

Documentation Location Variants

Let’s start with documentation within the program code. Though, this is not the aim of this article. In the open source projects , we often can notice that the documentation articles are kept in the same repository as the base code. For example, in the PHP fake fixtures library the documentation is in the README file, and if you want to read it to the end, you’ll have to scroll a little bit.In Guzzle, popular HTTP client for PHP, usage instructions are kept in a separate docs folder. Keeping documentation close to code is good and very handy. Downloading a vendors package once, you have code and documentation. If your library is not big, if it is stable and doesn’t involve frequent API changes in the future which result in permanent documentation rewriting, you can safely place the documentation in the repository of your project.

But everything has its reasonable limits. For example, if you are planning to create your own framework which is written by the team of developers and plan permanent releases, the framework has to be fully documented and what is more, the documentation must be translated into several languages. In this case putting documentation into repository of the project is not quite correct. Because constant corrections, updates, translations and debuggings would be quite typical. They will cause a large number of commits — fixes that spoil the history of the project. Navigating commit history when code changes are lost documentation changes is complex and uncomfortable.

In this case it is better to create a standalone repository for documentation, for example, as it was made for Symfony . GitHub, GitLab, Bitbucket also provide built-in WIKI tool that is attached to the project and is not a standalone repository. But you can also access it via Git which means you can copy all documentation, edit it in the editor you personally prefer, group modifications into commits, send them to server and get new comments.

Here’s an example of a well-organized WIKI for D3.js visualization library. Of course, it is possible to create a web site for a product and to put its documentation there. But if you use one of the methods described above, then you will be able to generate documentation web pages from your Git or WIKI repository — there’re tools for it. If you prefer overall solutions, you should pay attention to Confluence by Atlassian. It has much more features than WIKI-engine.

Commenting Code Inside The Code

Now let’s get back to documenting code in the code itself. I am writing this article based on my own experience but recently I’ve read “Clean Code” by Robert Martin so I’m going to cite this book when it’s relevant. The first message from Robert Martin is that the comment is the sign of failure. Comments are written only to indicate the wrong of a programmer , who couldn’t clearly express his idea through the programming language. The process of code analysis is a very broad concept and it goes far beyond this article. But let me share with you a trick for writing a really good code: you should write it so that it could be read as if it was sentences. The object-oriented programming is much more easier than functional, a widespread practice of naming classes with nouns and methods with verbs makes code look more natural. For example, we have a rabbit and let’s describe some of its basic functions as if they were an interface:

We simply create one object from Rabbit class:

Code is easily readable. Method run makes rabbit run, method stop is an intuitive command, it stops the previous action and rabbit stops. Now let’s teach our rabbit some tricks and make him run a fixed distance, which we will pass as parameter to the method run .

And he ran... But we can’t get what 100 means. Does this number mean minutes, meters, or foots? It could be fixed by means of commentary:

If a rabbit starts to “run” in several places and strings of your code, each of them needs additional commentaries. Commentaries will be duplicated and should be maintained in several places at once. The first thing you can do to avoid commentaries — is to replace number by variable.

In this case you don’t need a comment, because the code readability becomes a little bit better and you can see that the rabbit runs for 100 meters in the code. But the best variant will be to add context to the method name.

Rabbit is a noun, run is an adverb, in metres is a context, which we add to the method so that it captures the essence. It is possible to write methods using this scheme.

They will capture the essence of the method without additional comments. Just give your variables and methods correct names and you will reduce the amount of unnecessary commentaries in your code. Robert Martin gives a good advice on this point:

Don’t spend your time writing comments, which explain the mess you created, — spend it to fix it.

What if the comment is too long? How to turn it into the method name? You shouldn’t be afraid of long method names. Method length should be appropriate to capture the essence and don’t turn the method into an unreadable text. These methods are OK in this regard:

This is too much:

This method is hard to read, the architecture is incorrect. It can be refactored, for example, like this:

There are also exceptions in the length of method names. For example, when you write specifications for phpSpec , you may have no limits in the method length, the main thing is for your code to capture the essence. Here’s a code example from phpSpec documentation:

In specifications underscore is used in methods names and it’s easier to read long sentences this way. It doesn’t correspond to the PSR standard where camelCase is used, but it will be ok for readability of the tests.

The sense of appropriate length of the methods will come with time and experience. You may also look at examples from popular frameworks and libraries.

Comments Characteristics

Out-of-dateness.

Very often programmers change code, but forget to change comments. Especially when several programmers work on the same section. There are comments but they are written by one of the programmers and others don’t dare to change comments written by another programmer or too lazy to do this, or just don’t pay attention. As a result, these old out-of-date comments will only confuse the newcomer. The solution of this problem is quite simple. Alternatively, always pay attention to the up-to-dateness of commentaries but it will require your attention and effort. Or simply delete old comments. No comments is better than old outdated comments.

It means that comment is needless and is written in place where everything is clear without a commentary. Here’s an example of code with extra comments:

If we remove comments, code will remain clean:

Incompleteness

While writing a program, you can quickly write down your idea by placing comment in the code. When later you get back to that piece, the comment will remind you about your thought and you will be able to continue. After your idea was turned into code, you should remove the incomplete commentary or complete it. In other words, don’t make readers wonder what did you mean. As an example let’s start describe how rabbit eats:

What does “the rabbit will die” comment mean? It is clear when it happens in the real life. And what about the program? What did the author wanted to do after this? To release the memory taken by rabbit? To mention an exception and then finish it in another piece of code? In this code with rabbit nothing happens, the rabbit simply doesn’t get new calories when eating anything other than carrot and cabbage. But for a newcomer, who will be finishing the code, the author’s idea will remain unclear. It is likely, that a newcomer will delete the commentary and make it in his own way.

Unreliability

All men are liable to make mistakes. But programmers make them not only in code, but also in the comment blocks. Because of inattention, tiredness or lack of foreign language skills, comments are in a mess and confuse others. Unfortunately, it happens. The only advice I can give you is to be responsible for your comments. If you decided to write something, you should write it correctly. You should be a perfectionist while writing comments.

Non-obviousness

When unknown or non-obvious terms are used in a certain piece of code.

Here we can see that the growth of the rabbit is determined by some index, which depends on some factors. In this piece of code it is unclear what rabbit growth index is and how we can calculate it. It’s better to remove this comment and place a more detailed one after function.

So, We Shouldn’t Write The Comments At All, Right?

We should write them, but we have to take responsibility for them. There are crucial moments when they are necessary.

Informational Value

In some places comments are required. When it is necessary to explain the algorithm or when a group of programmers had to use “hacks” in the code and to leave a comment about it. To describe the reason why it was made, what the commentary is about and when it has to be corrected. But you should try to choose correct names for your variables and methods.

Regular expressions make me numb and I have to spend lots of time to understand them. In this case the informational won’t be excessive.

There many ways to solve the same task in programming . Each programmer has his own programming style, that’s why it can be difficult for him to scan through code written by somebody else. If you prefer a certain programming style or if you know from practice that algorithms you use are difficult to read, put some help text before the complex piece of code.

Notifications and warnings

There are some cases when you can’t use certain function, for example:

  • the necessary extension wasn’t installed in production or the vendor wasn’t updated;
  • it takes too long to execute one of the functions and it is better not to launch it;
  • because of the high resource requirements you can’t perform the cycle more than a certain number of times.

If you face such situation, comments will be very useful.

When a certain line of code is so important that you have to pay extra attention to it. I faced a problem once when multibyte functions encoding wasn’t set on staging and spent lots of time on searching and solving this issue. When the problem was solved, I added to my code a parameter manual with a commentary explaining why I did it:

One more advice from Dean Martin:

Don’t comment a bad code — rewrite it.

When you come across an unclear code and spent a lot of time trying to understand it, and then leave several comments for the next developer, you should understand that the code won’t become better. In this situation, if you understand the code, try refactoring it to make it more readable. The motto of the boy scout is “Leave the campground (code) cleaner than the way you found it”.

Making Documentation With The Help Of Doc.blocks

There is a separate kind of PHP comments that has its own standard — it is called DocBlock). There is a tool phpDocumentor (also known as phpDoc) for processing docblocks. It can read docblocks from code and create documentation based on them. DocBlock is a combination of DocComment and descriptions placed in it based on PHPDoc standard. There is a support of C-type multiple line comments (DocComment):

DocBlock is distinguished by the additional “star” sign /** in the beginning of the comment.

It is possible for DocBlock to have only one line but it must begin with /** nonetheless.

PHP Doc standard for DOCUMENTING PHP CODE is based on javaDoc for Java. An important component of Docbloc are tags and annotations which make comments semantic. Tag or annotations begin with @ , for example.

In the example above @param , @return and @throws are PHPDoc tags and they will be parsed using phpDocrumentor. @Rest\Post("/login") is an annotation to FOSRestBundle . The difference between annotations and tags is that tags only document PHP code and annotations add or change code. The distinctive feature of PHP annotations comparing with Java ones is that Java annotations are part of Java while PHP annotations are commentaries and to use them you should use reflection . Maybe in the future annotations will become part of PHP but currently to read them you should use this parser . It’s also worth noticing that if we change the beginning of dockblock from /** to /* this won’t be a dockblock, even if it contains tags or annotations, and the parser will ignore it.

Dockblocks are so widely used in the community of PHP programmers, that PSR-5 (PHP Standard Recommendation) is prepared on the dockblock basis. When I have been writing this article it was a draft copy.

In PHP using dockblocks you can document the following elements:

  • interfaces;
  • class constants;
  • properties;

It is also important that each dockblock can only be applied to one structure element. It means that each function, variable and class has its own dockblock.

There are many tags in PHPDoc but not all tags can be applied to all structure elements. Below there is a list of tags, which are already exist and their use and explanation.

  • @api (method) defines the stable public methods, which won’t change their semantics up to the next major release.
  • @author (in any place) defines the name or an email of the author who wrote the following code.
  • @copyright (in any place) is used to put your copyright in the code.
  • @deprecated (in any place) is a useful tag which means that this element will disappear in the next versions. Usually there is a comment with the code you should use instead. Also, most of the IDE highlight places where old methods are used. When it is necessary to clean the out-of-date code for the new release, it will be easy to search by this tag.
  • @example (in any place) is used for inserting a link to a file or a web page where the example of code usage is shown. Currently phpDocumentor claims that this tag is not fully supported.
  • @filesource (file) is a tag which you can place only at the very beginning of the php file because you can apply this tag only to a file and to include all code to the generated documentation.
  • @global (variable) — at this moment this tag is not supported, may be it will be implemented in the next versions when it is updated and reworked.
  • @ignore (any place) — a dockblock with this tag won’t be processed when generating documentation, even if there are other tags.
  • @internal (any place) — often used with tag @api, to show that the code is used by inner logic of this part of the program. Element with this tag won’t be included in the documentation.
  • @license (file, class) shows the type of license of the written code.
  • @link (any place) is used for adding links but according to the documentation this tag is not fully supported.
  • @method (class) is applied to the class and describes methods processed with function __call() .
  • @package (file, class) divides code into logical subgroups. When you place classes in the same namespace, you indicate their functional similarity. If classes belong to different namespaces but have the same logical characteristic, they can be grouped using this tag (for example this is the case with classes that all work with customer’s cart but belong to different namespaces). But it is better to avoid such situation. For example, Symfony code style doesn’t use this tag.
  • @param (method, function) describes the incoming function parameters. It’s worth noticing that if you describe the incoming parameters for a certain function using dockblocks, you have to describe all parameters, not only one or two.
  • @property (class) — as well as @method this tag is placed in the dockblock of the class, but its function is to describe the properties accessed with the help of magic functions __get() and __set() .
  • @property-read, @property-write (class) are similar to the previous tag but they process only one magic method __get() or __set() .
  • @return (method, function) is used for describing value returned by the function. You can specify its type and PhpStorm will pick it and give you different tips, but let’s talk about this later.
  • @see (any place) — using this tag you can insert links on external resources (just like with @link ), but it also allows to put relative links to classes and methods..
  • @since (any place) — you can indicate the version in which the piece of code appeared.
  • @source (any place, except the beginning) — with the help of this tag you can place pieces of the source code in the documentation (you set the beginning and the end code line)
  • @throws (method function) is used for specifying exceptions which can be called out by this function.
  • @todo (any place) — the most optimistic tag used by programmers as a reminder of what need to be done in a certain piece of code. IDE have an ability to detect this tag and group all parts of the code in a separate window which is very convenient for further search. This is the working standard and is used very often.
  • @uses (any place) is used for displaying the connection between different sections of code. It is similar to @see . The difference is that @see creates unidirectional link and after you go to a new documentation page you won’t have a backward link while @uses gives you a backward navigation link.
  • @var (variable) is used to specify and to describe variables similar to those used inside the functions and for the class properties. You should distinguish this tag and @param . Tag @param is used only in dockblocks for functions and describes the incoming parameters and @var is used to describe variables.
  • @version (any place) denotes the current program version in which this class, method, etc. appeares.

Outdated tags, which most likely won’t be supported in the future:

  • @category (file, class) was used to group packages together.
  • @subpackage (file, class) was used to mark the specific groups in the package.

Not all tags are equally popular. @var, @param, @return, @todo, @throws are most widely used. The others are less popular. And I have never met such tags as @property and @method , because it is dangerous to work with magic!

Ease To Use Dockblocks In IDE

If you are developing an open source project it is of course necessary to document public API using dockblocks. It not only gives you the ability to generate the final documentation but also allows other programmers to comfortably use your code in their IDE. As for your private code for the outsource project, dockblocks usage might seem a little bit irrelevant, but anyway I advise you to use them, because they will speed up your development.

Let’s take the most popular PHP IDE for PHP — PhpStorm . And look at the previous example of rabbit search:

What do variables $rabbits and $rabbit mean? PhpStorm knows nothing about this. PHP is weakly typed and the type of function result is not strictly specified in the description (hi there, PHP 7 where it will be implemented). That’s why you should tell your IDE how to deal with certain parts of code using dockblocks. There are several variants. You can do like this:

Or add tag @return in the method findRabbitsInLocations :

Please pay attention that we specify Rabbit[] and not Rabbit . Brackets make it clear that the array of class objects is returned. If we remove the brackets it means that the method returns one example of the class Rabbit. You can also write it like this @return null|Rabbit[] , the vertical stick means OR, in this case we point out that the method will return the array of rabbits or null .

No matter which way of pointing out the type you chose, now PHPStorm will show you some hints and tips after you type $rabbit-> and wait for a moment.

Code commenting and PHP documentation generation

This happens because PHPStorm knows that in the $rabbits variable is returned by Rabbit objects array. Next in foreach cycle $rabbit variable gets one element of the array which is an example of the Rabbit class and PHPStorm shows you all available public methods from this class. This way you can use classes with public methods written by your colleagues without taking your hands off the keyboard.

PHPStorm will provide you with hints and if the method has a clear name, you will be able to use it even without reading the source code and documentation.

One more useful feature available to you when using dockblocks with PHPStorm are warnings about wrong access parameters. Let’s finish writing the dockblock for one of the methods of Rabbit class:

Here we indicate that we have to use an integer for access (in PHP 7 it will be possible to set the number by means of syntax). What will happen if we pass an array in this method?

Code commenting and PHP documentation generation

PHPStorm highlights it and gives a hint that int is excepted here while you are using array . Very convenient, isn’t it? Hints will also be shown for mismatched classes and interfaces. If your method supports several types of incoming arguments, divide them using |. In this example if the method runInMetres() can work with arrays, you may write @param int|array $metres Metres and dockblock will stop showing warnings.

PhpStorm can also can generates dockblocks. Place the cursor on the line above the function, class or variable declaration, type /** and push Enter . IDE will generate a dockblock template you can change a little if you want. You can also run dockblock generation using Alt + Insert .

How Follow Commenting Styles

It’s good if all members of the team follow the rules of commenting PHPDoc. But in practice it’s rarely a case. Only perfectionists adhere to the standard, and also those who have been using dockblocks for a long time and it has become a habit for them. Some beginner programmers want to use dockblocks but sometimes forget to use them or don’t fully understand tags. Of course, there are tough nuts who don’t use dockblocks even if the team uses them.

To reduce the discomfort, you each member of the team should turn on dockblock inspection in the PhpStorm: Settings > Editor > Inspections > PHPDoc and mark all the checkboxes:

Code commenting and PHP documentation generation

Of course, you can’t force everyone to follow the rules. For the laziest people I’d like to provide an advice from “Clean Code” once again (it’s about code formatting, but implications are the same):

The rules must be respected by all members of the group. This means that each member of the group should be reasonable enough to know that no matter how the braces are placed, unless everyone agreed to place them in the same way.

Generating Documentation With PhpDocumentor

Now when everybody follows the rules and your code is full of dockblocks, you can generate the documentation. I write much about phpDocumentor documentation, only show you the most necessary commands, the other best practices on documenting php code you can find at the official website .

So you have to install phpDocumentor. It can be installed globally this way:

Or add it as a requirement to composer.json of your project.

And now when you are in the directory of the project which is full of dockblocks, simply run it from console.

As I already mentioned this is the most necessary set of options for documentation generation, the option -d src/ shows the way to the files, which you want to work with. The generated information will be located in the folder called output . Of course, this utility has different specifications and lots of features. Here’s a PHPDocumentor example code and you can choose the template which already exists or create your own.

Generating Documentation With Sami

OOne more PHP documenting tool based on dockblocks is a utility called Sami. Maybe it’s not as popular but I decided to mention it because the Symfony documentation is generated using Sami. And Fabien Potencier who created this utility mentions it in his blog .

Sami documentation generator differs from phpDocumentor because its configuration is stored in PHP files. In general it has more customization potential than phpDocumentor but you will have to configure it all manually, write some code in other words. You can even redefine different pieces of code which are responsible for documentation generation. All the necessary templates can be found at TWIG plus they are easy to redefine. For more detailed information about Sami go to the GitHub page .

This is just a small review of the problem of documenting code in PHP and commenting it. Here you will find a little bit of everything to encourage the desire for digging deeper into this topic. If you are a PHP beginner, I advise you to read a detailed documentation about phpDocumentor . If you are an experienced developer, you can share some of your personal experince by writing a comment below. ^_^

Best Farm Management Software in 2024

  • web-development ,

PhpStorm 2023.2 Help

Phpdoc comments.

For documentation comments, PhpStorm provides completion that is enabled by default. PhpStorm creates stubs of PHPDoc blocks when you type the /** opening tag and press Enter , or press Alt+Insert and appoint the code construct (a class, a method, a function, and so on) to document. Depending on your choice, PhpStorm will create the required tags or add an empty documentation stub.

If you need additional PHP-specific tags , PhpStorm provides code completion that suggests the tag names that are relevant in the current context. If a certain tag has multiple values, code completion provides a list of available values.

In PHPDoc comments, PhpStorm supports formatting options in compliance with the ZEND, PEAR, and other coding standards.

PHPDoc comments in your source code are available for Quick Documentation Lookup , which helps you get quick information for any documented symbol. You can open them for review in the Documentation tool window by pressing Control+Q .

Enable documentation comments

Press Control+Alt+S to open the IDE settings and then select Editor | General | Smart Keys .

In the Enter section, select or clear Insert documentation comment stub checkbox.

Generate a PHPDoc block for a code construct

To invoke generation of a PHPDoc block, do one of the following:

Place the caret before the required code construct (class, method, function, and so on), type the opening block comment /** , and press Enter .

In the editor context menu, select Generate | Generate PHPDoc blocks and choose the code construct to generate PHPDoc comments for.

Press Alt+Insert , then select Generate PHPDoc blocks , and choose the code construct to generate PHPDoc comments for.

Generate PHPDoc

PhpStorm analyzes the appointed code construct, extracts the data for parameters, return values, variables, or fields where possible, and on this basis generates a stub of a documentation block.

Describe the listed parameters and return values where necessary. PhpStorm checks and treats syntax in comments according to the code inspection settings .

Create tags in a PHPDoc comment block

PhpStorm analyzes the appointed code construct, extracts the data for parameters, return values, variables, or fields where possible, and on this basis generates a stub of a documentation block. If necessary, you can fill in the missing information.

In a PHPDoc block, select the desired empty line and press Control+Space .

Select the relevant tag from the suggestion list.

If the entered tag has several values, press Control+Space and select the desired value from the suggestion list.

Configure formatting inside PHPDoc comments

You can configure the appearance of PHPDoc comments, the presentation of class names, and the default tags sorting order. Note that the tag for properties is no longer configurable, the default @var tag is inserted automatically. For more information, refer to https://github.com/phpDocumentor/fig-standards/pull/55 .

In the Settings dialog ( Control+Alt+S ), go to Editor | Code Style | PHP .

Switch to the PHPDoc tab an configure the desired appearance options by selecting or clearing the checkboxes.

Specify how you want PhpStorm to present class names for properties, function parameters, return and throws values, and so on, by selecting or clearing the Use fully-qualified class names checkbox.

If necessary, define how the generated PHPDoc tags should be sorted by selecting the Sort PHPDoc tags checkbox.

Rendering PHPDoc comments

PhpStorm allows you to render PHPDoc comments in the editor. Rendered comments are easier to read, and they don't overload your code with extra tags.

Javadocs in the editing mode

Rendered PHPDoc comments allow you to click links to go to the referenced web pages, or view quick documentation for the referenced topics.

To change the font size, right-click a PHPDoc comment in the editor and select Adjust Font Size from the context menu. Note that the rendered comments use the same font size as the quick documentation popup.

Render PHPDoc comments by default

You can configure the IDE to always render PHPDoc comments in the editor.

Alternatively, in the Settings dialog Control+Alt+S , select Editor | General | Appearance and enable the Render documentation comments option.

Using PHPDoc code inspections

PhpStorm provides a set of predefined code inspections targeted at PHPDoc blocks. These inspections check whether classes, methods, functions, variables, and constants are supplied with a PHPDoc comment and whether the tags in the comment match the documented item.

Enable or disable a PHPDoc inspection

In the Settings dialog ( Control+Alt+S ), select Editor | Inspections .

On the Inspections page that opens, expand the PHPDoc node under PHP .

In the list of predefined inspections that opens, enable or disable an inspection by selecting or clearing the checkbox next to it.

Check that PHPDoc comments are provided for code constructs of a certain type

Enable the Missing PHPDoc Comment inspection.

In the Options area, select the checkboxes next to the required element type: class, method, function, variable, or constant.

To suppress reporting a Missing PHPDoc Comment error if a method or function does not contain any parameters or return values, select the Ignore PHPDoc without @param/@return checkbox.

  • Getting Started

Code Validation

  • Configuration
  • Error Codes
  • PHP Version Validation
  • Spell Checking
  • Syntax Validation
  • Unnecessary use declarations
  • Breakpoints
  • Configuring Xdebug
  • Debugging Overview
  • Exceptions or errors
  • Inspecting Data in the debugger
  • Javascript Debugging
  • Multi-user debugging
  • Output Window
  • Remote Debugging
  • Remote Debugging via SSH Tunnel
  • Troubleshooting
  • Using Callstack
  • Auto Import
  • Code Completion
  • Code Snippets
  • PHPDoc Comments
  • Regular Expressions
  • Smart Indenting
  • Suggestions
  • Syntax Highlighting
  • Word Highlighting
  • Installation Instructions
  • Installing PHP
  • Product Activation
  • Product Offline Activation
  • Subscriptions
  • Find All References
  • Go To Brace
  • Go To Definition
  • Navigate To
  • Navigation Bar
  • PHAR Archives
  • Solution Explorer
  • Details View
  • PHPUnit Tests
  • Laravel Support
  • New Project
  • New Project from Composer
  • New Project from Existing Code
  • New Project from Remote
  • Project Validation
  • Remote Explorer
  • PHPUnit Package
  • Run and Debug Tests
  • Test Configuration
  • Test Explorer
  • Writing Test Case
  • ActivityLog.xml
  • PHP Version
  • Remote Development
  • Debug Overview
  • Launch Profiles
  • Xdebug on Linux
  • Xdebug on Mac
  • Xdebug on Windows
  • Code Actions
  • Code Editor Overview
  • Code Formatting
  • Customize Formatting
  • HTML/CSS/JSS
  • Inlay Hints
  • Navigation Overview
  • Refactoring
  • Selecting PHP
  • Signature Helper
  • Writing PHPDoc
  • Installation
  • Web Extension

PHP Documentary Comments (PHPDoc)

PHPDoc is a standard way of documenting and annotating the PHP code. It is a well-known format of block comments prefixed with /** characters, and it is used to annotate functions, classes, properties, and also local variables. With PHPDoc it is possible to provide documentation, additional type information, and other information for the editor.

A regular PHPDoc comment looks like the following (in case of a function documentation):

In this case it would be placed right above the function declaration in the PHP code. The editor would provide a short description whenever it provides foo code completion, and it would treat the function as it accepts one argument of type array of integers, and returning a value of type integer.

Generate PHPDoc

The PHP Editor automatically generates corresponding PHPDoc stub upon typing /** . This works above functions, classes, interfaces, traits, properties, and constant declarations.

Place caret above function, class, namespace, property, or constant declaration. Type /** and the corresponding PHPDoc block will be generated. The PHP Tools Editor also infers the types and possible exceptions being thrown by the function, so it gets annotated as well.

The PHPDoc is inserted as a code snippet with placeholders. Missing information can be filled in. To jump between fields, press TAB .

This behavior can be turned off or on (it is on by default) in the Visual Studio's Options window (Tools / Options), in Text Editor / PHP / Advanced, the option Generate PHPDoc comments for /** .

php advanced options

Completing PHPDoc Tags

The PHP Tools Editor provides completion and snippets for PHPDoc tags as well. Place the caret inside PHPDoc block and either type @ or press Ctrl+Space .

Complete the tag with TAB to insert it as a full snippet, or just confirm the selection to insert the tag name.

Documentation

The text inside the PHPDoc is used for documentation purposes. It can be one or more lines of text. It will be available in quick tool tips, in signature help, or in code completion tool tips.

tooltip with summary from PHPDoc

The quick tool tip above shows information from the corresponding PHPDoc comment.

Excluding from IntelliSense

In some cases, the function represents a dummy declaration and is not supposed to be used by developers or being seen in IntelliSense at all. Use @ignore PHPDoc tag to annotate such function.

Example of a function that won't be listed in IntelliSense.

Type Annotations

There are several PHPDoc tags that may be used to annotate the function parameters, function return value, property type, constant type, or a variable type. The standard PHPDoc tags are the following:

  • @param : specifies the parameter type and description in the form: @param (type) ($name) (description) .
  • @return : provides information about the return value in the form: @return (type) (description) .
  • @var : allows to annotate properties, constants, class constants: @var (type) (description) .
  • @global : annotates global variables within the current scope: @global (type) ($name) (description) .

In order to annotate a local variable, the @var tag is used:

The annotation can be placed on a single line as well:

Or the variable name can be omitted completely if it can be inferred from the statement below it:

The editor understands generic type annotations (also known as templates).

The class/function with template type arguments is annotated with @template PHPDoc tag, optionaly specifying the template type constrain:

templated class annotation

Notice, the tooltip for class MyClass shows the template arguments as well. The type constrain Traversable is used whenever the type U is not bound (whenever the editor does not know the actual assigned type), so it can provide code analytics and code completion.

In order to use the template type arguments, specify them as any other type within PHPDoc.

php generic instance

Notice, the editor will substitute T with ArrayObject and U with string . This results in working code completion, and the editor will properly provides completion after foo() which is expected to return either ArrayObject or array<string> .

Psalm/PHPStan

The 3rd party code linters like Psalm or PHPStan introduce extended PHPDoc type annotations. Those are supported by the PHP Tools Editor as well.

Types can be specified in various forms including:

  • callable(mixed...):(Option<T>)
  • array<int, mixed>
  • non-empty-string
  • class-string
  • class-string<T>

PHPDoc tags may be prefixed with @psalm- or @phpstan- . Such tags are handled as well.

The editor respects those annotations but may not take the full advantage of them (yet).

Class Annotations

There are several PHPDoc tag specific to class/interface declartion.

  • @extends allows to describe the base class name including its generic type arguments. Example: @extends ArrayObject<int, MyUser>
  • @implements allows to describe an implemented interface with its generic type arguments. Example: @implements Iterable<int>
  • @use is used above a trait use to describe its generic type arguments.
  • @method declares a method in case the class provides dynamic methods through magic __call() function. This information is used by the code completion to provide this additional method in the list.
  • @property similarly to @method allows to define a dynamic property.
  • @mixin tells the editor to include members of another type (aka mixin) into this class.

The PHPDoc is validated for valid type names, valid tag names, and common typos.

For the quick fixes there are same rules as for the PHP code; invalid type names may get completed namespace. In case the type name is ambiguous or needs to get fully qualified, the \ prefix may get inserted by the code completion or by the quick fix.

The PHPDoc comment block is formatted according to the statement below which it corresponds with. The block is formatted according to standards, indented.

Introduction to PhpDoc

how to write php documentation

If you’ve ever tried to read code written by someone other than yourself (who hasn’t?), you know it can be a daunting task. A jumble of “spaghetti code” mixed with numerous oddly named variables makes your head spin. Does this function expect a string or an array? Does this variable store an integer or an object? After countless hours of following the threads of code and trying to understand what each bit does, it’s not uncommon to give up and just rewrite the whole thing from scratch – a task that wastes far too much of your precious time.

PhpDoc, short for PhpDocumentor, is a powerful tool that allows you to easily document your code via specially formatted comments. The documentation will be available not only in the source code, but also in professional documentation extracted using either the web or command-line interface. The result can be in various formats such as HTML, PDF, and CHM. Additionally, many IDEs that provide code-completion can parse PhpDoc comments and provide useful features such as type-hinting. By using PhpDoc, you can make it easy for others (and yourself) to understand your code – weeks, months, and even years after you’ve written it.

The easiest way to install PhpDoc is with PEAR. Of course, before you can do so you must have PEAR installed. If you don’t, follow the instructions at pear.php.net/manual/en/installation.php .

In this article I’ll show you how to use PhpDoc to generate gorgeous and user-friendly documentation from beginning to end.

A DocBlock is a multi-line C-style comment used to document a block of code. It begins with /** and has an asterisk at the start of each line. Here’s an example:

DocBlocks consist of three sections: short description, long description, and tags. All three sections are optional.

The short description is a succinct description terminated by either a new-line or a period. PhpDoc’s parsing routines are smart; it will only end the short description if the period is at the end of a sentence.

The long description is where the bulk of the documentation goes; it can be multi-line and as long you wish.

Both the long and short descriptions may contain certain HTML elements for formatting. HTML tags that aren’t supported will be displayed as plain text. PhpDoc can generate the documentation in multiple formats, though, so the HTML tags aren’t necessarily rendered as they would in an HTML file; the actual formatting depends on the generated file format. If you need to display an HTML tag as text, use double brackets. For example:

The tags section of a DocBlock contains any number of special tags denoted by the @ symbol. The tags are used to specify additional information, such as the expected parameters and their type. Most tags must be on their own line, with the exception of certain tags which may be inline. Inline tags are surrounded with curly braces and may be in both the long and short description. For a full list of tags, check out the relevant PhpDoc documentation .

If you need to start a line with the @ symbol but you don’t want it to be interpreted as a tag, you can escape it with a backslash.

PhpDoc will automatically recognize textual lists in the long and short descriptions and it will parse them. However, it won’t parse nested lists correctly. If you want to use nested lists, use the HTML tags. Here is an example to illustrate what I mean:

PhpDoc packages are used to group related code elements in the generated documentation. You can specify packages for files and classes and the documented code they contain will inherit the package from them. To specify a package, set the @package tag in a file-level or class-level DocBlock (file-level and class-level DocBlocks will be discussed further is the following section). A package name may contain letters, numbers, dashes, underscores, and square brackets (“[” and “]”).

Here is an example of defining a file’s package:

If you have multiple levels of packages and sub-packages, you can define a sub-package with the @subpackage tag. Here is an example:

If a file or class doesn’t specify a package it will be set to the default package, “default”. You can specify a different package to be used by default when generating the documentation via the -dn command-line option.

What Can I Document?

Not all code elements can be documented with DocBlocks. Here is a list of code elements that may be documented:

Functions and methods

  • Class properties
  • Global variables
  • include() / require()

All of these elements can use certain common tags, but each has tags that are specific to that element. I’ll go over a few of the elements and the tags normally used to document them.

File-level DocBlocks are used to document the contents of a file. It is highly recommended to include a file-level DocBlock in every file you document, and in fact PhpDoc will display a warning if one is not found when generating documentation.

Most elements are documented by placing a DocBlock before the element, but files are an exception (since you can’t write anything before a file). File-level DocBlocks are placed on the first line of the file.

A file-level DocBlock usually contains the tags @package , @subpackage , @license , and @author . The @package and @subpackage tags were discussed earlier. The @license tag is used to specify a URL to an external license that covers your code. The tag must contain the URL to the license and optionally a title. The @author tag is used to specify the author of the file. It must contain the author’s name and optionally an email address in angle brackets.

Unlike most elements, a file-level DocBlock must contain a @package tag in order to be parsed properly.

Here is a complete example of a file-level DocBlock:

A class-level DocBlock is placed before a class definition and should describe the meaning of the class. Like file-level DocBlocks, class-level DocBlocks usually contain the tags @package , @subpackage , and @author . Here is an example:

Functions and methods are documented identically in PhpDoc. (For those who may not be familiar with the terminology, a method is just a function within a class.) Functions and methods usually contain the @param and @return tags in their DocBlocks. The @param tag is used to document the expected type of a parameter. It contains three sections: the parameter, the data type, and an optional description. The @return tag is used to document the return type. It contains two sections: the data type and an optional description. In both tags, the data type can be either a valid PHP data type, a class name, or “mixed”. It can also contain multiple options separated by a pipe.

Generating Documentation

Once you’ve documented your PHP code, you’ll want to generate user-friendly documentation from it. To do so, run the PhpDoc command-line tool.

The -d option specifies a comma-separated list of directories containing files to document, and -t the path to generated docs. -ti is used to specify the project title, and -dn to set the default package name. Finally, -o specifies the documentation format. PhpDoc has a wide selection of formats to choose from. A full list is available on the PhpDoc website .

You can find out more about the command-line tool by executing the help command as follows:

Once you run the command, the documentation path you specified should contain the generated docs.

For those of you who aren’t comfortable using the command-line interface, PhpDoc also has a web interface available. It’s outside of this articles scope to discuss it at length, but you can read more about it on PhpDoc’s official website, phpdoc.org .

In this article I’ve given you a first look at PhpDoc and its many powerful features. I have explained the purpose of DocBlocks and their components; I have shown you how to organize your documentation using packages; I have explained which code elements can be documented and some common examples of doing so; finally, I have shown you how to generate documentation from your source code. I highly recommend that you start using PhpDoc in your own projects, if even only to document the most important parts. It is very straight-forward and will save you and your co-workers countless hours of nail-biting and hair-pulling.

Image via Zadorozhnyi Viktor / Shutterstock

Documentation

The PHP Manual is available online in a selection of languages. Please pick a language from the list below.

Note, that many languages are just under translation, and the untranslated parts are still in English. Also some translated parts might be outdated. The translation teams are open to contributions.

View Online: English , Brazilian Portuguese , Chinese (Simplified) , French , German , Japanese , Russian , Spanish , Turkish

For downloadable formats, please visit our documentation downloads page.

Information about php.net URL shortcuts can be found by visiting our Navigation tips & tricks page .

More documentation

  • If you are interested in how the documentation is edited and translated, you should read the Documentation HOWTO .
  • PHP-GTK related documentation is hosted on the PHP-GTK website.
  • Documentation of PEAR and the various packages can be found on a separate server.
  • You can still read a copy of the original PHP/FI 2.0 Manual on our site, which we only host for historical purposes. The same applies to the PHP 3 Manual .
  • The PHP 4 and PHP 5 documentation has been removed from the manual, but archived versions still exist. For more information, please read Documentation for PHP 4 and Documentation for 5 , respectively.

To Top

Include an external example file with syntax highlighting

Description.

The example tag can be used to parse an example file for syntax highlighting and linking to documentation. This versatile tag attempts to read the file from the full path specified, and will accept any path that http://www.php.net/fopen will accept. phpDocumentor checks the path to ensure that the file retrieved has a valid .php extension as defined in phpDocumentor.ini, and then opens the file. It will parse the file, and output syntax-highlighted source with line numbers, links to documentation and will then add a link to the documentation to that file.

If given an absolute path, phpDocumentor will not search for the example file any further. If given a relative path (no leading c:\ or /) phpDocumentor searches for examples files first in the directory specified by the -ed, --examplesdir command-line, if present. As of phpDocumentor 1.2.1, it will next search for the file in an examples/ subdirectory of the current file's directory. Otherwise, it will search for a subdirectory named "examples" in the top-level parsing directory, and if not found, in the top-level directory.

The top-level parsing directory is simply the directory that every file parsed has in common.

The @filesource tag serves a similar purpose, but instead of parsing a separate file, it parses the current file's source.

To do an inline code example, use the html tag <code> or the new inline {@example} tag

Here's an example:

  •  * My function
  •  * Here is an inline example:
  •  * <code>
  •  *  <?php
  •  * echo  strlen ( '6' ) ;
  •  *  ?>
  •  * </code>
  •  * @example /path/to/example.php How to use this function
  •  * @example anotherexample.inc This example is in the "examples" subdirectory
  • function mine()

phpDocumentor

Basic syntax.

This chapter gives an overview of the syntax of "DocBlocks". The precise effect of a tag including examples are provided in different chapters which are accessible via this document.

What is a DocBlock?

A DocBlock is a special type of comment that can provide verbose information about an element in your code.

The information provided in this type of comment can be used by developers to gain understanding of the function of a given element; but it is also used by IDEs to provide (among others) auto-completion and by phpDocumentor to generate API documentation.

This is an example of a DocBlock as it can be encountered:

Which elements can have a DocBlock

Structural Elements can all be preceded by a DocBlock. The following elements are counted as such:

require(_once) include(_once) class interface trait function (including methods) property constant variables, both local and global scope.

A DocBlock roughly exists of 3 sections:

  • Summary; a one-liner which globally states the function of the documented element.
  • Description; an extended description of the function of the documented element; may contain markup and inline tags.
  • Tags; a series of descriptors for properties of this element; such as @param and @return.

The summary is used to give an impression of the function of the documented element. This can be used in overviews to allow the user to skim the documentation in search of the required template.

Summaries should always end in either a full stop, or 2 consecutive new lines. If it is not closed like this then any description will be considered as part of the summary.

Summaries shall be plain text. Unlike other text elements in DocBlocks Markdown is not supported, nor are tags.

A full stop means that the dot ( . ) needs to be succeeded by a new line. This way it is possible to mention abbreviations as "e.g.", version numbers or other texts containing dots without ending the summary.

Description

The description contains concise information about the function of the documented element. It is allowed, and encouraged, to use Markdown markup to apply styling.

The following list has examples of types of information that can be contained in a description:

  • Explanation of algorithms
  • Code examples
  • Array specification
  • Relation to other elements
  • License information (in the case of file DocBlocks)

Descriptions can also contain inline tags. These are special annotations that can be substituted for a specialized type of information (such as {@link}). Inline tags are always surrounded by braces.

A complete listing is provided in Inline tag reference .

Tags represent meta-data with which IDEs, external tooling or even the application itself know how to interpret an element.

phpDocumentor understands and uses (almost) all types supported by phpDocumentor. A complete listing is provided in Tag reference .

In addition phpDocumentor is able to understand, and link to, the annotations of Doctrine2.

Inheritance

Docblocks automatically inherit the Summary and Description of an overridden, extended or implemented element.

For example: if Class B extends Class A and it has an empty DocBlock defined, then it will have the same Summary and Description as Class A. No DocBlock means that the 'parent' DocBlock will not be overridden and an error will be thrown during parsing.

This form of inheritance applies to any element that can be overridden, such as Classes, Interfaces, Methods and Properties. Constants and Functions can not be overridden in and thus do not have this behavior.

Please note that you can also augment a Description with its parent's Description using the { @inheritdoc } inline tag.

Each element also inherits a specific set of tags; which ones depend on the type of element.

The following applies:

Please note that @subpackage tags are only inherited if the parent class has the same @package. Otherwise it is assumed that the parent class is part of a library which might have a different structure.

Search results

How to Document Your Code Properly

We're glad you're interested in developing for OpenEMR, but before you start adding, it's important that you remember to document your code. What follows, is a basic guide for how to document what you are doing.

  • 1.1 DocBlock Example
  • 1.2.1 File-Level DocBlock
  • 1.2.2 Element-Level DocBlock
  • 1.3.1 Page Level Doc Block:
  • 1.3.2 Element Level DocBlock:
  • 1.3.3 In-line DocBlock Tags
  • 1.3.4 HTML markup in DocBlocks
  • 1.3.5 DocBlock Templates
  • 2 Where to Use a DocBlock
  • 3 Documentation in Your Development Repository
  • 4 Inline Documentation
  • 5 Update "Live" Wiki Documents
  • 6 External Links

What is a 'DocBlock'?

A DocBlock is format that evolved from C++. It is a clean, standards compliant way of documenting your code, which allows for easy reading and parsing. A DocBlock begins with the three character line /** and each line of the body begins with a space-asterisk * and the characters */ make the last line of the DocBlock. A DocBlock is placed immediately above the element being documented. A Page-level DocBlock is the first DocBlock and contains the @package tag. Ordinarily there would be an element-level DocBlock next following the page-level DocBlock.

DocBlock Example

A basic DocBlock looks like:

Examples for OpenEMR

File-level docblock.

Every file in the OpenEMR codebase should have a file-level DocBlock that contains basic information. Here's an example:

Element-Level DocBlock

An element-level DockBlock should precede at least each function and each class in your code.

Most Available Tags

Here is a partial list of tags available in PhpDocumentor. See PhpDocumentor Manual Listing them as Page- or Element-Level is not meant to restrict usage, but some tags are indeed intended for certain DocBlock levels.

Page Level Doc Block:

The page level DocBlock should appear at the top of the file, after the opening <?php . PhpDocumentor parses a DocBlock as a page-level DocBlock if it precedes another DocBlock or if it is the first DocBlock and contains the @package tag.

Element Level DocBlock:

PhpDocumentor is capable of automatically documenting these elements: include statements, define statements, functions , procedural pages , classes , class variables , and class methods . The element level DocBlock is placed immediately above the element.

For the @param and @return tags, the datatype should be a valid PHP type (int, string, bool, etc), a class name for the type of object returned, or simply "mixed". If you want to explicitly show multiple possible return types, list them pipe-delimited without spaces (e.g. "@return int|string"). If a class name is used as the datatype in the @return tag, PhpDocumentor will automatically create a link to that class's documentation. In addition, if a function returns multiple possible values, separate them using the | character, and PhpDocumentor will parse out any class names in the return value. PhpDocumentor will display the optional description unmodified.

In-line DocBlock Tags

Inline tags display in the documentation text flow where they appear. My guess is the {@inheritdoc} is of the most interest, since it can simplify documentation of parent and child classes. PhpDocumentor will automatically inherit the @author tag, @version tag, and @copyright tag from a parent class. Reference the manual for more information.

The documentation for class foo will include the documentation from class bar.

HTML markup in DocBlocks

The next example illustrates the use of selected html markup tags to format documentation features. The <pre> notes... </pre> construct may the the most useful to separate some formatted text from the rest of your description. This is from PhpDocumentator Converter.inc. The @abstract tag is no longer used. You will also notice the @internal tag which allows some documentation to be seen only by certain people.

You can use the following html markup tags: <b> <i> <pre> <code> <var> <ul> <ol> <li> Be sure to use the corresponding closing tags as well.

DocBlock Templates

As the last example, I want to show the DocBlock template which can simplify documentation for a succession of similar code elements. The format is /**#@+ the required six characters to indicate a template, one or more @tagname value being the body, and the finishing characters */ . DocBlock templates are applied to all document-able elements until the ending template marker: /**#@-*/ is seen.

The example from the tutorial shows the template below and all elements up to var $publicvar will be documented with the tags @access private and @var string, with "Two words" included in the documentation for var $_var8. The template will not apply to var $publicvar.

Where to Use a DocBlock

  • All Files should begin with a page-level DocBlock with at least:
  • @package OpenEMR
  • Classes - For classes you want to use at least an @author tag
  • Functions - For functions you want to use:
  • Use a @param tag for each field your function accepts
  • Use a @return tag to explain the data to be returned

Documentation in Your Development Repository

The main API documentation will actually be produced in the main repository. However, you will benefit by having your own documentation capability in your git branch repository on your computer. The api documentation generated by PhpDocumentor and similar programs is an html web page and is created in a specified directory. You point your web browser to that directory and the index.html page will have the links to your documentation. The PhpDocumentor is available as a Pear package and there are other documentation programs as well. PhpDocumentor is the program of choice, but it does not handle namespaces or closures in PHP and will crash if it encounters these new features.

  • PhpDocumentor superceded by v2, but my choice anyway
  • phpDocumentor2 (requires php-5.3 minimum, but still alpha release as of 6/25/2012)
  • PHPDoctor download and unpack in your working directory
  • ApiGen uses Nette framework, create API documentation from PHP source (php-5.3 min)
  • doxygen (DockBlock capability assumed as a subset of JavaDoc)

The command to create documentation with PhpDocumentor is:

and the command line options are seen with

The other programs are similar, so see the documentation for whichever program you choose.

Each program, to my knowledge, has an output parameter which lets you store the documentation in the specified directory. In your git repository, I suggest including the documentation directory in the .gitignore file, so your generated documentation will not be part of the git commit process, but still available for your reference.

The various tags may not be recognized by all programs and html markup capability may not be consistent. See NetBeans wiki for some discussion on using the different programs.

Inline Documentation

Obviously classes and functions aren't the only places where things are going that need some documentation. For, foreach, while and if statements all can get quite large and might need a little note above them. If you think you have a statement like this that needs a note, please make sure to do so.

Update "Live" Wiki Documents

There are several "live" wiki documents that should get updated with the codebase:

1. New Database Tables:

2. New Options (ie. Globals):

3. New User Specific Options:

4. New Lists:

5. New ACOs:

External Links

  • http://manual.phpdoc.org/HTMLSmartyConverter/HandS/phpDocumentor/tutorial_elements.pkg.html
  • http://manual.phpdoc.org/HTMLSmartyConverter/HandS/phpDocumentor/tutorial_phpDocumentor.howto.pkg.html#basics.starting
  • Developer Guide

Navigation menu

Openemr project wiki, personal tools.

  • View source

wiki navigation

  • Main wiki page
  • Recent changes
  • Random page
  • What links here
  • Related changes
  • Special pages
  • Printable version
  • Permanent link
  • Page information

GNU Free Documentation License 1.3

  • This page was last edited on 22 July 2017, at 19:10.
  • Content is available under GNU Free Documentation License 1.3 unless otherwise noted.
  • Privacy policy
  • About OpenEMR Project Wiki
  • Disclaimers

IMAGES

  1. How to Write Good Documentation

    how to write php documentation

  2. PHP Write File

    how to write php documentation

  3. PHP Write File

    how to write php documentation

  4. PHP Documentation Tool 2.1 review and download

    how to write php documentation

  5. How to create PHP documentation in PhpStorm

    how to write php documentation

  6. How to Write PHP Scripts (with Pictures)

    how to write php documentation

VIDEO

  1. PHP Code Documentation

  2. How to Write Project Documentation using Chat Gpt

  3. 1

  4. php project

  5. php project

  6. PHP Programming Tutorial

COMMENTS

  1. What Is PHP Programming?

    Want to learn more about what makes the web run? PHP is a programming language used for server-side web development. If this doesn’t make sense to you, or if you still aren’t quite sure what PHP programming is for, keep reading to learn mor...

  2. Using PHP and MySQL in Web Development

    In the world of web development, developers have a wide array of options when it comes to scripting languages, data retrieval, and other details. As a result, a plethora of combinations do exist. However, using PHP and MySQL in web developm...

  3. How to Find the Right Template to Write a Document for Free

    Writing documents can be a daunting task, especially if you’re not sure where to start. Fortunately, there are many free templates available online that can help you get started. Here are some tips on how to find the right template to write...

  4. PHP Documentation Standards

    Summaries should be clear, simple, and brief. Avoid describing “why” an element exists, rather, focus on documenting “what” and “when” it does something. A

  5. Code commenting and PHP documentation generation

    PHP Doc standard for DOCUMENTING PHP CODE is based on javaDoc for Java. An important component of Docbloc are tags and annotations which make

  6. PHPDoc comments

    PHPDoc comments · In the Settings dialog ( Ctrl Alt 0S ), go to Editor | Code Style | PHP. · Switch to the PHPDoc tab an configure the desired

  7. PHPDoc Comments

    PHPDoc is a standard way of documenting and annotating the PHP code. It is a well-known format of block comments prefixed with /** characters, and it is used to

  8. How do you document your PHP functions and classes inline? [closed]

    I'm not interested in generating manuals -- I want to know how to generate the type of code commenting above, or "inline documentation." PHP

  9. Introduction to PhpDoc

    Once you've documented your PHP code, you'll want to generate user-friendly documentation from it. To do so, run the PhpDoc command-line tool.

  10. Documentation

    Documentation. The PHP Manual is available online in a selection of languages. Please pick a language from the list below. Note, that many languages

  11. @example

    @example. Include an external example file with syntax highlighting. by Gregory Beaver. Tag Documentation written by [email protected].

  12. Basic Syntax

    example This is an example function/method parameter description. * @param

  13. How to Document Your Code Properly

    Page Level Doc Block: The page level DocBlock should appear at the top of the file, after the opening <?php . PhpDocumentor parses a DocBlock as

  14. PHPDoc Documentation

    } A realistic example. The code below is a sample class showing PHPDocumentor in action. PHPDocumentor can parse any valid PHP code, but