I am confused about when to use the null
as a type when describing variables with PHPDoc. Are type hints supposed to describe hopes and expectations for external callers to anticipate and comply with, or are they supposed to document all possible types of the variable even if the hope is it will be one very specific type in practice?
Example 1: default values. The following function only expects non-null values. But if no value is passed, it defaults to null
and checks for that explicitly as a way to determine whether or not anything was passed, and returns a special value for that case. Hopefully no external caller will pass anything except an integer. Should null
be used in the @param
type as below, or should it only specify int
since that's what we want passed if anything is passed?
/**
* @param int|null $bar
*/
function foo($bar = null) {
if(is_null($bar)) {
return 'ABC';
}
return doSomething($bar);
}
Example 2: instance properties. We only want $bar to contain integers. That said, if nothing is set for bar then the default PHP value for this instance property is null. Do I need to account for this every place that uses $bar, with a possible null type as below?
class Foo {
/**
* @var int|null
*/
public $bar;
/**
* @param int|null $bar
*/
public setBar( $bar) {
$this->bar = $bar;
}
/**
* @return int|null
*/
public function getBar() {
return $this->bar;
}
}
Basically I find myself littering nearly every @param
and @var
declaration with |null
because technically it could be that value. But in practice it shouldn't be. Should I expect nearly all of my types to contain the possibility of null
or should that be assumed, and I should avoid specifying it unless I expect to set or receive a value of null
explicitly?