Search code examples
phpstringphp-7null-coalescing-operator

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 ?


Solution

  • I believe you may be able to typecast your value of $x,

    example:

    function foo(?string $x) : string {
        $a = (string) $x;
    
        return $a;
    }
    

    This should yield,

    var_dump(foo("test"));
    
    string(4) "test"
    

    And,

    var_dump(foo(null));
    
    string(0) ""
    

    Hope this is what you were looking for.