Skip to content

07: DocComments on Function Parameters

Read parameter descriptions directly from reflection. This is useful for a command help generator that needs to display an explanation beside each argument.

  • PHP 8.6 CLI. Confirm the version with php --version.
  • Review the previous chapter if you’re following the series in order.

Allow about 10 minutes for the walkthrough and exercise.

A runnable parameter-doccomments.php example.

Run the following from the root of the Code with PHP repository.

Terminal window
php code/php-8-6/07-parameter-doccomments/parameter-doccomments.php
parameter-doccomments.php
<?php
declare(strict_types=1);
function importOrders(
/** Local CSV path */
string $path,
/** Maximum rows in one batch */
int $limit = 100,
bool $verbose = false,
): array {
return compact('path', 'limit', 'verbose');
}
foreach (new ReflectionFunction('importOrders')->getParameters() as $parameter) {
printf("%s %s\n", $parameter->getName(), $parameter->getDocComment() ?: '(undocumented)');
}
path /** Local CSV path */
limit /** Maximum rows in one batch */
verbose (undocumented)

The declaration can attach a /** ... */ comment to each parameter. getDocComment() returns the raw comment or false when no comment exists. A doc generator can use that distinction to supply a fallback.

  • Use a documentation comment beginning with /**. Ordinary block comments never appear in reflection.

Add a documented bool $dryRun = false argument and verify that the report prints its name and comment.

Continue with Inspect Property Read and Write Access.