Where can I read about conditionals done with “?” and “:” (colon)? [duplicate]

╄→гoц情女王★ 提交于 2019-12-17 10:06:45

问题


Possible Duplicate:
Reference - What does this symbol mean in PHP?

I've been doing conditionals with if/else or a year or so now. Looking at some new code, I'm seeing a conditional that appears to use ? and : instead of if and else. I'd like to learn more about this, but I am not sure what to google to find articles explaining how it works. How can I do it?


回答1:


It's the Ternary Operator.

Basic usage is something like

$foo = (if this expressions returns true) ? (assign this value to $foo) : (otherwise, assign this value to $foo)

It can be used for more than assignment though, it looks like other examples are cropping up below.

I think the reason you see this in a lot of modern, OO style PHP is that without static typing you end up needing to be paranoid about the types in any particular variable, and a one line ternary is less cluttered than a 7 line if/else conditional.

Also, in deference to the comments and truth in naming, read all about the ternary operators in computer science.




回答2:


That would be the conditional operator. It's pretty much a single line if/then/else statement:

if(someCondition){
    $x = doSomething();
}
else{
    $x = doSomethingElse();
}

Becomes:

$x = someCondition ? doSomething() : doSomethingElse();



回答3:


It is:

condition ? do_if_true : do_if_false

So, for example in the below, do->something() will be run.

$true = 1;
$false = 0

$true ? $do->something() : $do->nothing();

But in the below example, do->nothing() will be run.

$false ? $do->something() : $do->nothing();



回答4:


This is the ternary operator in PHP. It's shorthand for if/else, format is:

condition ? true expression : false expression;


来源:https://stackoverflow.com/questions/4055355/where-can-i-read-about-conditionals-done-with-and-colon

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!