Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct usage of ?? operator

Tags:

php

php-7

In my project, i have an ajax.php which is handling all AJAX POST requests. It gets the command, verifies all the required arguments exist and pass it off to the relevant class.

I've seen the new '??' operator and have started verifying the POST arguments like this,

$name = $_POST['name'] ?? die('{"result":0, "data":"name not provided"}');
$state = $_POST['state'] ?? die('{"result":0, "data":"state not provided"}');

Which I think looks better than,

$name = isset($_POST['blah']) ? $_POST['blah'] : die('{"result":0, "data":"blah not provided"}');  

I've deployed and confirmed it is working but Intellij is chucking a hissy fit about unreachable code after the first usage. I'd like to know if i'm either misusing the syntax and could potentially be fixed or if Intellij just isn't on the ball.

I'm always paranoid about bad practices so would like to know your opinions on both the syntax usage as well as the whole ajax.php. Is it bad to have a page dedicated to basically verifying post arguments exist? (it doesn't verify the actual data, just that it has data). I've also wondered if i should split ajax.php into a route to try and split it up? Would you ever consider doing something like

foreach (['name', 'state'] AS $arg) {
  $$arg = $_POST[$arg] ?? die("{\"result\":0, \"data\":\"$arg not provided\"}");
}

which can then either return the processed value or throw an exception/die if missing or would you prefer having each argument per line?

like image 618
Lokicat Avatar asked Jun 08 '16 00:06

Lokicat


1 Answers

It's just a glitch in Intellij. I get the same with PHPStorm 10. You can easily test this to demonstrate your code works as you'd expect it to, and that's the proof in the pudding, not how some IDE happens to (miss-)parse it.

If you felt like being helpful, perhaps raise a ticket with JetBrains?

I'll leave the second part of your overall question as - as I indicated in my comment above - it is a separate question, and should be presented accordingly. And probably over on Code Review. If you do shift it there... make sure to cross ref back here :-)

like image 153
Adam Cameron Avatar answered Nov 15 '22 09:11

Adam Cameron