PHPDoc optional parameter

user2742648 picture user2742648 · Nov 18, 2012 · Viewed 25.5k times · Source

There are already 2 similar questions of this type here on SO but none of the answers seem to work.

PHPDoc doesn't seem to recognize optional parameters in my functions as optional, for example:

/**
 * Opens the connection and sets encoding
 * 
 * @param string $encoding Encoding.
 */
public function __construct($encoding='UTF-8') 
{
    $this->connect_mysqli();
    $this->set_encoding_mysqli($encoding);
}

Shouldn't it recognize $encoding as being optional or am I missing something here? I really tried to google and read the documentation but all I found is:

If you are not indicating in the actual code that the parameter is optional (via "$paramname = 'a default value'"), then you should mention in the parameter's description that the parameter is optional.

So I see no problem with my code, but all I get in documentation is: "__construct(string $encoding)", no sign anywhere that parameter is optional.

Answer

KingCrunch picture KingCrunch · Nov 18, 2012

Strictly speaking, PHP doesn't know "optional parameters", but parameters with default values, that can be omitted when the function or method is called. OK, that's at the end an optional parameter, but your

@param string $encoding Encoding.

is completely correct here, because the default value is a string. What the documentation tries to tell you is that you should mention it yourself like

@param string $encoding (optional) Encoding.

I agree with you, that a notation like

__construct([$encoding])

or

__construct($encoding = 'UTF-8')

would be nice. You can post a bug report

https://github.com/phpDocumentor/phpDocumentor2/issues?state=open

Update: Realised, that this already mentioned https://github.com/phpDocumentor/phpDocumentor2/search?q=optional&type=Issues