Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional nullable parameters in PHPDoc

Imagine that we have method with optional nullable argument (PHP 7.0) like in this example:

/**
 * @param Type1 $foo 
 * @param Type2 $bar
 */
 function myFunction(Type1 $foo, Type2 $bar = null)
 {

 }

Unfortunately it's not clear from the PHPDoc documentation, what is the right way to mark the second argument optional and nullable.

Typically I use "Type2|null" notation:

/**
 * @param Type1 $foo 
 * @param Type2|null $bar
 */
 function myFunction(Type1 $foo, Type2 $bar = null)
 {

 }

Actually this is my preferable way, because it explicitly describes all the possible types. But I heard complaints that is not obvious from the doc if the parameter is optional or not.

I'm aware of, seams like, unofficial convention "(optional)"

/**
 * @param Type1 $foo 
 * @param Type2 $bar (optional)
 */
 function myFunction(Type1 $foo, Type2 $bar = null)
 {

 }

I don't like this approach, because, technically, you can explicitly provide NULL as a second argument. And it's not clear from the phpdoc.

Generally speaking, I can even use them together:

 * @param Type2|null $bar (optional)

But it doesn't look nice, IMHO.

Could you provide me some feedback or, even better, some links to corresponding coding standards / style guides?

like image 447
Alex Avatar asked Mar 02 '18 16:03

Alex


1 Answers

@param Type2|null $bar

is the proper way, from the perspective of phpDocumentor... see the last three arguments of the getOption() method as shown here.

like image 161
ashnazg Avatar answered Oct 16 '22 11:10

ashnazg