Current Location: Home> Latest Articles> How to Write Standardized PHP Function Documentation?

How to Write Standardized PHP Function Documentation?

M66 2025-07-08

Introduction

Writing clear and comprehensive documentation for PHP functions is crucial for modular, maintainable, and team-collaborative code. Adhering to standardized documentation practices ensures consistency and ease of understanding.

Naming Conventions

Function names should start with a lowercase letter and use underscores to separate words (e.g., my_function). Additionally, follow PSR-2 naming conventions by using camel case for class and method names (e.g., MyFunction).

@param Tag

Use the @param tag to specify the type and description of function parameters.

Example:

/**
 * @param string $name Username
 * @param string $password Password
 */
function login(string $name, string $password) {}

@return Tag

Use the @return tag to specify the type and description of a function's return value.

Example:

/**
 * @return bool Whether the login was successful
 */
function login(string $name, string $password): bool {}

@throws Tag

Use the @throws tag to specify the exception types and descriptions that the function might throw.

Example:

/**
 * @throws InvalidArgumentException If $name or $password is empty
 */
function login(string $name, string $password): bool {}

Comment Block Example

Here’s an example of a function comment block that conforms to the PSR-5 standard:

/**
 * Login user
 * @param string $name Username
 * @param string $password Password
 * @return bool Whether the login was successful
 * @throws InvalidArgumentException If $name or $password is empty
 */
function login(string $name, string $password): bool {}

Practical Examples

No-argument Function

Example: Get the current time.

/**
 * Get the current time
 * @return string Current time string
 */
function get_current_time(): string {
    return date('Y-m-d H:i:s');
}

Multiple Argument Function

Example: Calculate the sum of two numbers.

/**
 * Calculate the sum of two numbers
 * @param int $a First number
 * @param int $b Second number
 * @return int The sum
 */
function sum(int $a, int $b): int {
    return $a + $b;
}

Things to Remember

  • Always follow standardized documentation practices.
  • Write concise and accurate descriptions.
  • Ensure all potential parameters, return values, and exceptions are covered.
  • Regularly update documentation to reflect code changes.