Zenzs
Zenzs

Reputation: 138

Arguments and type declarations using "?" for nullable values

PHP Version 7.3.8

References: https://www.php.net/manual/en/functions.returning-values.php#functions.returning-values.type-declaration

I've been reading this sentence on the above page:

As of PHP 7.1.0, return values can be marked as nullable by prefixing the type name with a question mark (?). This signifies that the function returns either the specified type or NULL.

The following values were passed and the results are documented here:

$marketID = 'abcdef'; // Result is: Throws a type error.
$marketID = '12345';  // Result is: It will be cast as an int.
$marketID = 12345;    // Result is: It will successfully execute.
$marketID = null;     // Result is: It will successfully execute.

// App controller

protected function setMarketID(?int $marketID)
{
    $this->marketID = $marketID;
    return $this;
}

protected function getMarketID()
{
    // Will return an int or null.
    return $this->marketID;
}

Is it considered acceptable to code like this. IE: Use (?) in this way to accept type and null as the manual states return values can be marked... NOT incoming values but it works? (Please see Edit)

Edit for anyone in the future reading this post:

// Will return an int or null.
If you pass an int argument to the setter the getter will automatically return an int and if you pass a null argument to the setter the getter will automatically return null.

@yivi

Yes very helpful thanks. I have added strict types and it works perfectly and I have also added your advice of declaring a return value. IE:

protected function getMarketId():?int

And again works perfectly.

Upvotes: 1

Views: 895

Answers (1)

yivi
yivi

Reputation: 47301

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.

Upvotes: 1

Related Questions