2012-08-25 122 views
24

我正在寻找扩展我的PHP知识,并且我遇到了一些我不确定它是甚么或者甚至是如何搜索它的东西。我正在看php.net isset代码,并且我看到isset($_GET['something']) ? $_GET['something'] : ''

我了解正常的isset操作,如if(isset($_GET['something']){ If something is exists, then it is set and we will do something }但我不明白?,重复get,或:''。有人能帮我解决这个问题,或者至少让我指出正确的方向吗?

+2

相关http://stackoverflow.com/questions/3737139/reference-what-does-this-symbol- mean-in-php – Musa

+1

可能的重复[什么是PHP? :运算符调用,它是做什么的?](http://stackoverflow.com/questions/1080247/what-is-the-php-operator-called-and-what-does-it-do) – Niko

回答

50

它通常被称为'速记'或Ternary Operator

$test = isset($_GET['something']) ? $_GET['something'] : ''; 

意味着

if(isset($_GET['something'])) { 
    $test = $_GET['something']; 
} else { 
    $test = ''; 
} 

进行分解:

$test = ... // assign variable 
isset(...) // test 
? ... // if test is true, do ... (equivalent to if) 
: ... // otherwise... (equivalent to else) 

或...

// test --v 
if(isset(...)) { // if test is true, do ... (equivalent to ?) 
    $test = // assign variable 
} else { // otherwise... (equivalent to :) 
1

?被称为三元(有条件)运算符:example

6

这就是所谓的三元运算符,它主要用于代替if-else语句。

在你给它可以用来检索数组给出isset值的例子返回true

isset($_GET['something']) ? $_GET['something'] : '' 

相当于

if (isset($_GET['something'])) { 
    $_GET['something']; 
} else { 
    ''; 
} 

当然,除非你指定的没有多大用处它的东西,甚至可能为用户提交的值分配一个默认值。

$username = isset($_GET['username']) ? $_GET['username'] : 'anonymous' 
4

您曾遇到过ternary operator。它的目的是基本的if-else语句。以下几段代码可以做同样的事情。

三元:

$something = isset($_GET['something']) ? $_GET['something'] : "failed"; 

的if-else:

if (isset($_GET['something'])) { 
    $something = $_GET['something']; 
} else { 
    $something = "failed"; 
} 
3

从PHP 7,你可以把它写更短:

$age = $_GET['age']) ?? 27; 

这意味着,如果在将设置为$age VAR的URL提供年龄PARAM,或将默认为27

查看所有new features of php 7

1

如果你想要一个空字符串默认那么首选方法是这些(根据您的需要)之一:

$str_value = strval($_GET['something']); 
$trimmed_value = trim($_GET['something']); 
$int_value = intval($_GET['somenumber']); 

如果URL参数something并不在URL中存在然后$_GET['something']将返回null

strval($_GET['something']) - >strval(null) - >""

和你的变量$value设为一个空的字符串。

  • trim()可能超过strval()根据代码者优先(如名称参数可能希望使用它)
  • intval()如果只是数值预计,默认值是零。 intval(null) - >0

情况来考虑:

...&something=value1&key2=value2(典型值)

...&key2=value2(参数从网址$ _GET失踪将返回null吧)

...&something=+++&key2=value(参数" "

为什么这是首选的a pproach:

  • 它适合在一条线上,并清楚发生了什么事情。
  • 这是可读比复制/粘贴错误的$value = isset($_GET['something']) ? $_GET['something'] : '';
  • 降低风险或一个错字:$value=isset($_GET['something'])?$_GET['somthing']:'';
  • 这是与旧的和新的PHP兼容。

更新 严格模式可能需要这样的事情:

$str_value = strval(@$_GET['something']); 
$trimmed_value = trim(@$_GET['something']); 
$int_value = intval(@$_GET['somenumber']);