Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert nullable variable to non nullable type?

I have function which will receive parameter ?string

public function func(?string $x): string
{
    $x = trim(strtolower($x));
    $x = preg_replace('/\s+/', ' ', $x);
    $x = str_replace(' ', '-', $x);
    return $x;
}

running ./vendor/bin/phpstan analyse give those errors:

Parameter #1 $str of function strtolower expects string, string|null given.              
Parameter #3 $subject of function preg_replace expects array|string, string|null given.  
Parameter #3 $subject of function str_replace expects array|string, string|null given.   

strtolower needs string and preg_replace&str_replace need array|string

what is the best way to solve this without changing param from ?string $x to string $x?
in otherwords how to change var type from string|null to string ?

like image 490
Khaled Alam Avatar asked Oct 23 '25 12:10

Khaled Alam


1 Answers

While PHP can convert null to an empty string with casting, you really have to ask yourself why this function should even accept a null value in the first place.

If null means you have some default value for $x, then that seems perfectly logical, and you can use null coalescing to make $x the default string value if $x is null.

$x = $x ?? 'default';

However, the above could be more effectively resolved by defining 'default' in the signature:

function func(string $x = 'default')

But based on your code, there really isn't any reason for null to be passed to this function. In my opinion, that's a code smell and should not be allowed. This function only works with strings, so don't allow nulls to begin with. The null value should then be handled before it reaches this function, by the consumer.

like image 181
Devon Avatar answered Oct 25 '25 02:10

Devon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!