Nullable return types in PHP7

PHP 7.1 Now supports nullable return types. The first RFC I linked to is the one they went for:

function nullOrString(int $foo) : ?string
{
    return $foo%2 ? "odd" : null;
}

old answer:

Since my comment was actually an answer to the question:

PHP 7 won’t support nullable return-types just yet, but there’s an RFC out to address just that, it aims to land in PHP 7.1. If it passes, the syntax would then affect all type-hints (both return types and type-hints):

public function returnStringOrNull(?array $optionalArray) : ?string
{
    if ($optionalArray) {
        return implode(', ', $optionalArray);//string returned here
    }
    return null;
}

There’s also a competing RFC to add union types, which would be able to do the same thing, but would look different:

public function returnStringOrNull(array|null $optionalArray) : string|null
{
    if ($optionalArray) {
        return implode(', ', $optionalArray);//string returned here
    }
    return null;
}

For now, though, you’ll have to write:

public function returnStringOrNull( array $optionalArray = null)
{
    if ($optionalArray) {
        return implode(', ', $optionalArray);
    }
}

Or just return an empty string to be consistent with the return type, and check falsy value:

public function returnStringOrNull( array $optionalArray = null) : string
{
    if ($optionalArray) {
        return implode(', ', $optionalArray);
    }
    return '';
}
//call
$string = $x->returnStringOrNull();
if (!$string) {
    $string = $x->returnStringOrNull(range(1, 10));
}

Leave a Comment