A php if statement with one equal sign…? What does

2020-08-12 09:06发布

I'm attempting to troubleshoot a problem, and need to understand what this if statement is saying:

if ($confirmation = $payment_modules->confirmation()) { 

All the resources I can find only show if statements with double equal signs, not single. Is this one of the shorthand forms of a php if? What is it doing?

(If it's actually wrong syntax, changing it to a double equal sign doesn't resolve the problem. As-is, in some scenarios it does return true. In the scenario I'm troubleshooting, it doesn't return true until after I refresh the browser.)

Any help is greatly appreciated!!!

标签: php
5条回答
做个烂人
2楼-- · 2020-08-12 09:45

The code works because an assignment returns the value assigned, so if $payment_modules->confirmation() is true, $confirmation will be set to true, and then the assignment will return true. Same thing for false.

That's why you can use a command to assign to many variables, as in a = b = 0. Assigns zero to b and returns that zero. Therefore, it becomes a = 0. And a receives zero and it will return that zero, which can or can not be used.

查看更多
成全新的幸福
3楼-- · 2020-08-12 09:49

This will first assign the value of $payment_modules->confirmation() to $confirmation. The = operator will evaluate to the new value of $confirmation.

This has the same effect as writing:

$confirmation = $payment_modules->confirmation();
if ($confirmation) {
  // this will get executed if $confirmation is not false, null, or zero
}
查看更多
Animai°情兽
4楼-- · 2020-08-12 09:54

Sometimes people like to do an assignment and then check if the assignment went through okay. Pair this up with functions that return false (or equivalent) on failure, and you can do an assignment and a check at the same time.

In order to understand this, remember that assignments are a kind of expression, and so (like all expressions) have a return value. That return value is equal to whatever got put into the variable. That is why you can do something like

a = b = c = 0;

to assign all of those variables at the same time.

查看更多
做自己的国王
5楼-- · 2020-08-12 09:56

It's a form of shorthand, which is exactly equivalent to this:

$confirmation = $payment_modules->confirmation();
if ($confirmation) {

}
查看更多
老娘就宠你
6楼-- · 2020-08-12 10:05

= means assignment ( $a = 1 ), == is for comparison ( true == false is false ). I think in your example it should use = because it assigns it to the return value of confirmation, which should be something that evaluates to true.

Try doing a var_dump:

var_dump( $payment_modules->confirmation() );

See what boolean it evaluates to, and from there you can troubleshoot. Post more code if you want more help.

class test() {
    public function confirmation() { return true; }
}

$boolean = test::confirmation();
var_dump( $boolean );

Will equate to true

查看更多
登录 后发表回答