PHP Parameters – How to Use Setter with One Parameter and Null Default Value

nullparametersPHP

Which solution is most logical? The value can be null, but when not null it must be a string.

This (First):

function setValue(string $value = null);

To me this is bad; since we can now call the method without anything:

$dependency->setValue(): 

Or this (Second)?

function setValue($value)
{
    if(is_string($value) OR $value == null)
    {
        //allow value
    } else {
        //throw error
    }
}

Or this (Third)?

function setValue(string $value)
{
    $this->value = $value;
}

//client
function client()
{
    $value = "test";
    if($value)
    {
        $this->dependency->setValue($value);
    }
}

This solution does not allow null to be set.

I prefer the Second solution. To only downside is the interface does not clearly show what values are accepted.

Best Answer

With PHP 7.1 it's actually quite simple:

public function setValue(?string $value)
{
    $this->value = $value;
}

or when you want it to default to null when calling it $object->setValue();

public function setValue(string $value = null)
{
    $this->value = $value;
}
Related Topic