PHP return in combination with null coalescing operator

287 Views Asked by At

I wonder if it is possible to exit a function e.g. by return in the second statement of a null coalescing operator in PHP.

I want to use this to check some POST data in a function and exit the function if a POST var is not set.

This would be clean code without the painful if(isset(...)).

Example script file:

 <?php

// Controller

$id = $_POST['id'] ?? add();

function add(){
  $var1 = $_POST['var1'] ?? return;  // <-- is this possible or some similar solution?
  $var2 = $_POST['var2'] ?? return;

  // All POST vars are set: do something
  // ...
}
1

There are 1 best solutions below

1
Michał Rosłaniec On

No, this is not possible. Code below may not be a one line solution as you initially wanted but is still shorter than:

I must write if(isset(_POST['var1']) { $var1 = _POST['var1']; } . So I always have to refer to _POST['var1'] twice: once for evaluation, once for setting the variable in the function for further processing.

function add() {
    if (!$var1 = $_POST['var1'] ?? null) {
        return;
    }
    // $var1 declared and has value here
}

You can also throw an exception like this:

// ...
$var1 = $_POST['var1'] ?? throw new \Exception('...');
// ...