开发者

return variable in if statement - multiple attempts possible?

开发者 https://www.devze.com 2023-03-27 23:18 出处:网络
i am unsure weather i am terming this correctly, but i think the following code will be pretty self explaintory:

i am unsure weather i am terming this correctly, but i think the following code will be pretty self explaintory:

function a($p){
    if($p===true){
        return 'yep';
    }
    else{
        return false;
    }
}

if($test=a(true)){
    echo $test; // this will echo out 'yep'
}

the above code works as expected. what i am trying to accomplish is something like this:

function a($p){
    if($p===true){
        return 'yep';
    }
    else{
        return false;
    }
}

if($test=a(false)||$test=a(true)){
    开发者_如何学Pythonvar_dump($test); // this will show $test being bool(true) NOT yep
}

is this possible without doing an intermediate function?

i have also tried:

if($test=(a(false)||a(true)){ ... }

to no avail.


$test = a(false) || $test = a(true)

will be evaluated as

$test = ( a(false) || $test=a(true) )

Logical operators always return a boolean value, so the result of the || expression will be assigned to $test.

If you want that the expressions above assigns the string to $test, then you have use or which has a lower precedence then the assignment operator ( I would prefer this way in this context):

$test = a(false) or $test = a(true)

DEMO

Or you set the parenthesis correctly:

($test = a(false)) || ($test = a(true))
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号