3

I have a function to populate an Object.

public static function populateObj($data) {
    $obj = new Obj();
    $obj->setVal1($data['val1']);
    $obj->setVal2($data['val2']);
    $obj->setId($data['id']);
    return $obj;
}

If all values are given with the parameter $data it works fine. But if someting is missing it throws an error.
Is there a shorter and easier or better way to set null as default than this:

$data['val1'] ? $obj->setVal1($data['val1']) : $obj->setVal1(null);
...
1
  • should be !empty($data['val1']) ? $obj->setVal1($data['val1']) : $obj->setVal1(null) or isset($data['val1']) ? $obj->setVal1($data['val1']) : $obj->setVal1(null) Commented Jan 4, 2018 at 18:20

3 Answers 3

6

You can merge with a default array, then $data will contain all of those keys:

$data = array_merge(['val1'=>null, 'val2'=>null, 'id'=>null], $data);

In PHP >= 7.0 you can use the Null Coalescing Operator:

$obj->setVal1($data['val1'] ?? null);
Sign up to request clarification or add additional context in comments.

Comments

2

That is perhaps the fastest (fewest typed words) way to do it. Another that may be faster, if it is worth it to you is to make a class and a constructor with default values. array_pad() with array_merge() may also be worth looking at, depending on your application.

Comments

1

In PHP 7+ you can use ?? a.k.a null coalesce

$obj->setVal1($data['val1']??null);
$obj->setVal2($data['val2']??null);
$obj->setId($data['id']??null);

See an example here

The null coalescing operator (??) has been added (in PHP7) as syntactic sugar for the common case of needing to use a ternary in conjunction with isset(). It returns its first operand if it exists and is not NULL; otherwise it returns its second operand.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.