Home » Php » php – How to document a parameter that expects a constant

php – How to document a parameter that expects a constant

Posted by: admin July 12, 2020 Leave a comment

Questions:

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){
        // ...
    }
}
How to&Answers:

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

Answer:

Here located information about how to document constant using phpdoc

const/define means the same in php