What does this syntax ( page = $page ? $page : 'default' ) in PHP mean?

十年热恋 提交于 2019-12-14 01:19:33

问题


I'm new to PHP. I came across this syntax in WordPress. What does the last line of that code do?

$page = $_SERVER['REQUEST_URI'];
$page = str_replace("/","",$page);
$page = str_replace(".php","",$page);
$page = $page ? $page : 'default'

回答1:


It's an example of the conditional operator in PHP.

It's the shorthand version of:

if (something is true ) {
    Do this
}
else {
    Do that
}

See Using If/Else Ternary Operators http://php.net/manual/en/language.operators.comparison.php.




回答2:


That's the ternary operator:

That line translates to

if ($page)
    $page = $page;
else
    $page = 'default';



回答3:


It's a ternary operation which is not PHP or WordPress specific, it exists in most langauges.

(condition) ? true_case : false_case 

So in this case the value of $page will be "default", when $page is something similar to false — otherwise it will remain unchanged.




回答4:


It means that if $page does not have a value (or it is zero), set it to 'default'.




回答5:


It means if the $page variable is not empty then assign the $page variable on the last line that variable or set it to 'default' page name.

It is called conditional operator




回答6:


More verbose syntax of the last line is:

if ($page)
{
    $page = $page;
}
else
{
    $page = 'default';
}



回答7:


That's the so-called conditional operator. It functions like an if-else statement, so

$page = $page ? $page : 'default';

does the same as

if($page)
{
    $page = $page;
}
else
{
    $page = 'default';
}


来源:https://stackoverflow.com/questions/2099834/what-does-this-syntax-page-page-page-default-in-php-mean

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