1

I need use a ternary conditional result inside my called function. Is this possible?

(new SaveData($query))->idSaved() ? letsgo('gotrue', idSaved()) : letsgo('gofalse');

It's possible use result of my ternary inside that? In this case, idSaved() return the Inserted ID on my database.

Actually I use:

$res = new SaveData($query);
$res->idSaved() ? letsgo('gotrue', $res->idSaved()) : letsgo('gofalse');
EvandroPH
  • 21
  • 3
  • Don't you mean `$res ? letsgo('gotrue', $res) : letsgo('gofalse');`? – Barmar Apr 06 '22 at 19:52
  • 1
    The more ternaries you add the less readable, and therefore maintainable, the code gets. Barmar's solution certainly works, but it is yet more confusing to read. I would honestly suggest doing away with the ternary altogether and fleshing it out to and `if(){}else{}` block. – Sammitch Apr 06 '22 at 20:09
  • On a side note, I'd recommend refactoring (or writing a wrapper for) `idSaved()` so you pass it only one value, and it determines whether to use 'gotrue' or 'gofalse' based on whether the value received is true or false. This will simplify your calls to `idSaved()` and eliminate the need for [magic numbers](https://stackoverflow.com/questions/47882/what-is-a-magic-number-and-why-is-it-bad) in every call. – kmoser Apr 06 '22 at 20:21
  • @Barmar yes. Edited! – EvandroPH Apr 07 '22 at 01:06
  • I corrected the second line, I had copied it wrong – EvandroPH Apr 07 '22 at 01:08
  • @Sammitch then you think is more readable/recommended: `if ($res = new SaveData($query)) { letsgo('gotrue', $res->idSaved()); } else { letsgo('gofalse'); }` . Nice suggestion. I'll think about it. – EvandroPH Apr 07 '22 at 01:18

1 Answers1

1

You can assign the variable inside the ternary:

($res = (new SaveData($query))->idSaved()) ? letsgo('gotrue', $res) : letsgo('gofalse')
Barmar
  • 741,623
  • 53
  • 500
  • 612