-2

I am starter php developer, I know, if else, or, elseif... but I don't understand those : ? and other symbols. So can you tell me what this lines mean:

$success = $success ? $b->save(false) : $success;

if (!success) // shouldn't this be without "!"
    $transaction->commit(); // this means "do the job, if ok"
  else
    $transaction->rollBack(); // this means "don't do the job, if not ok"

Also, can you tell me how to call this symbols, I don't know their name and so I can't find tutorials about them

Irakli
  • 1,151
  • 5
  • 30
  • 55

3 Answers3

4

It's pretty common in a lot of languages, you can find this Ternary Operations for example in javascript aswell

It is a short hand for an if/else.

The part before the ? is the condition, the next part is the code to execute if the condition returns true, and the last part (after the :) if it returns false:

condition ? if true : if false;

$a = 3 > 5 ? 'three is greater than five' : 'three is lesser than five';

In this case $a would be three is lesser than five;

I would recommend ternary operations only for very simple conditions/results, if not, you end up writting less maintainable code, sacrificing shortness for legibility

aleation
  • 4,796
  • 1
  • 21
  • 35
2

the above code looks like if $success from previous transactions was true , try $b->save(false) and then put the returned value from $b->save(false) into $success.

$b->save(false) means save without validation, and after successful save, will return true

then the if part is very clear

Developerium
  • 7,155
  • 5
  • 36
  • 56
  • But shouldn't there be if (success) {$transaction->commit();} – Irakli Jan 13 '14 at 12:40
  • that makes more sense if some other stuff went ok, do the commit, but that depends on the logic previously implemented which you havn't shown us, so I can't say – Developerium Jan 13 '14 at 12:46
2

That's a Ternary Operator, a short form for an if statement.

$success = $success ? $b->save(false) : $success;

is the same as

if($success) {
    $success = $b->save(false);
} else {
    $success = $success;
}
Maarkoize
  • 2,601
  • 2
  • 16
  • 34