Is there a way in PHP to use null coalesing/nullsafe operators to default to not set any value?

58 Views Asked by At

I only see use cases were null coalesing can be used to chain values, but not to omit any value.

Am I missing something essential or is there really no shorthand way to write this:

$model->name = "Example";

if(isset($input->name)) {
    $validName = $this->doSomeValidationEventualyReturnNull($input->name);
    if($validName) {
        $model->name = $validName;
    }
}
1

There are 1 best solutions below

5
On BEST ANSWER

I can propose this one liner, has something to do with null coalescing.

$model->name = isset($input->name) ? ($this->doSomeValidationEventualyReturnNull($input->name) ?? $model->name) : $model->name;