As of PHP 7.1 you can specify a nullable return type with a question mark in front of the return type. This means that you can either return an integer or a null value. Note that not returning anything also technically means returning a null value.
Nullable types ¶ Type declarations for parameters and return values can now be marked as nullable by prefixing the type name with a question mark. This signifies that as well as the specified type, null can be passed as an argument, or returned as a value, respectively.
Type declarations can be added to function arguments, return values, and, as of PHP 7.4. 0, class properties. They ensure that the value is of the specified type at call time, otherwise a TypeError is thrown. Note: When overriding a parent method, the child's method must match any return type declaration on the parent.
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;
}
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));
}
Nullable Types are available in PHP 7.1.
This is a syntax example:
public function getName(): ?string
{
return $this->name; // name can be null
}
PHP 7.1 is now GA and you can upgrade from PHP 7.0 (there are only few backward incompatible changes that you have to check)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With