Nullable Return Types in PHP7

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));
}

Returning NULL with return type declarations

PHP 7.1 added nullable types, where you put a question mark before the type name to mark the return type as accepting both that type and null:

public function getId(): ?int {
/* … */
}

If you're still on PHP 7.0, I suggest omitting the type declaration and using a docblock.

How does PHP 7 return type coercion work for null?

This is expected and by design. You can find the original RFC for this feature at http://wiki.php.net/rfc/return_types.

Specifically there is a section Disallowing NULL on Return Types which states:

this type of situation is common in many languages including PHP. By design this RFC does not allow null to be returned in this situation for two reasons:

  1. This aligns with current parameter type behavior. When parameters have a type declared, a value of null is not allowed.
  2. Allowing null by default works against the purpose of type declarations. Type declarations make it easier to reason about the surrounding code. If null was allowed the programmer would always have to worry about the null case.

Now, I can't see in this rfc any talk of type conversion, whereas the official docs do, so chances are null isn't converted simply because the RFC was explicit in saying it wasn't to work. Personally I think leaving null as the odd one out is weird. It was potentially also being consider as linked with the nullable types rfc, which may have made a difference to how null was determined to work.

I can't say I personally agree with how it's worked out, but I'm not a core developer :).

Arguments and type declarations using ? for nullable values

You haven't declared a single return type in your example.

In setMarketId() you declared a parameter type (?int). So this method will accept either an integer or null.

If you declare you are using strict_types, then the method will not even accept '12345' or 123.5, and only accept a proper int or a null value.

Declaring a return value like the one that you expect (and consistent with what getMarketId() would return), would be accomplished like this:

protected function getMarketId():?int
{
return $this-marketId;
}

Of course it is "acceptable" to declare a type is nullable. When it makes sense or not it will depend entirely on your application, but it's a very common usage.

Is it possible to specify multiple return types on PHP 7?

As of PHP 8+, you may use union types:

function test(): FailObject|SuccessObject {}

Another way, available in all versions since PHP 4, is for the two objects to share an interface. Example:

interface ReturnInterface {}
class FailObject implements ReturnInterface {}
class SuccessObject implements ReturnInterface {}
function test(): ReturnInterface {}

In this example, ReturnInterface is empty. Its mere presence supports the needed return type declaration.

You could also use a base, possibly abstract, class.


To me, for this use case, interfaces are more clear and more extensible than union types. For example, if I later want a WarnObject I need only to define it as extending ReturnInterface -- rather than going through all signatures and updating them to FailObject|SuccessObject|WarnObject.

PHP Nullable Types not working as expected

Yer kinda confusing the concept of optional arguments with the concept of nullable ones.

An optional arguments means you don't need to pass it cos it's optional.

A nullable argument means that whilst the argument needs to be of a certain type, that null is also valid (where it wouldn't be if it wasn't nullable). Nullability doesn't mean you don't need to pass anything; you still do. It can just be null.

If you want to have an integer argument which is optional and considered null if not passed, then combine yer two examples:

function getCustomerId(?int $id=null)
{
return $id ?: 2;
}

Ref: PHP > New Features > Nullable types

PHP nullable type declaration

There is no difference as string is nullable by default.

Btw, this was introduced in PHP 7.1: https://www.php.net/manual/en/migration71.new-features.php

PHP 7.1 Doctrine proxy issue with nullable types

I fixed the problem by upgrading from the version 2.6 to the version 2.8 of doctrine/doctrine-common library

What value should I return in case of error if I want to declare a function type in PHP?

In PHP 7, Type declarations for parameters and return values can now be marked as nullable by prefixing the type name with a question mark.

e.g. function coefficient(int $pack_size = null) : ?object

From https://www.php.net/manual/en/migration71.new-features.php



Related Topics



Leave a reply



Submit