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

Time:05-19

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;
    }
}

CodePudding user response:

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;
  • Related