Álvaro González
Álvaro González

Reputation: 146450

How to document a parameter that expects a constant

What's the recommended way to document function or method parameters whose value is expected to be a predefined constant? So far, I use the data type of the constant and I add a little explanation later.

E.g.:

<?php

class Foo{
    const METHOD_GET = 'get';
    const METHOD_POST = 'post';

    /**
     * Load a new foo
     *
     * @param string $method HTTP method to use (either Foo::METHOD_GET or Foo::METHOD_POST)
     */
    public function load($method=Foo::METHOD_POST){
        // ...
    }

    /**
     * Sort current foo
     *
     * @param int $sort_order Sort order (either SORT_ASC or SORT_DESC)
     */
    public function sort($sort_order=SORT_ASC){
        // ...
    }
}

Upvotes: 12

Views: 4162

Answers (2)

igorsantos07
igorsantos07

Reputation: 4686

#1: PHPStorm-only option, available in all PHP versions

While non-canonical, it's currently possible to achieve auto-completion with a list of options for a param inside PHPStorm, in case it's common in your team. It uses the new PHP8 Annotations, but PHP8 is not required - since the objective is just to parse the source and get auto-completion.

Since it's (unfortunately) not part of the official PHPDoc standard, it gets a bit ugly for simple methods since you need a full (and maybe long) extra line to properly document the options, but it's still better than no docs.

See their official post on the topic, but here's an example from the same post:

enter image description here

#2: PHP-wide option, but only from 8.1 up

PHP 8.1 will feature Enums, which are the "official" version of value lists. Enums can be used as the type of a param, and this would solve the same issue we're having, in an official way and that PHPDoc can support without including new syntaxes - and also actually enforcing the param check during runtime! You can see more how that would work in another PHPStorm post (no affiliation at all, I just happened to discover the feature through them, so I'm honoring the source).

Upvotes: 7

ashnazg
ashnazg

Reputation: 6688

Given that you can use a known class as the dataype in param and return tags, I would also expect that you can use a known constant. When you want to specify multiple type options, you just delimit the list with pipes. Modifying your example:

/**
 * Load a new foo
 *
 * @param Foo::METHOD_GET|Foo::METHOD_POST $method HTTP method to use
 */
public function load($method=Foo::METHOD_POST){
    // ...
}

Since the datatype in this case is a known internal-to-the-class value, it might even work without the classname prefix:

* @param METHOD_GET|METHOD_POST $method HTTP method to use

Upvotes: 7

Related Questions