简体   繁体   English

将PHP if / else语句转换为使用三进制格式

[英]Converting a PHP if/else statement to use ternary format

I want to convert this if/else statement to ternary format: 我想将此if / else语句转换为三元格式:

function session_active()
{
  if ($_SESSION['p_logged_in']) { 
    return true; 
  } 
  else { 
    return false; 
  }; 
}

I tried: 我试过了:

function session_active()
{
  ($_SESSION['p_logged_in'] ? true : false);
}

but it always returns false. 但它总是返回false。

I am looking at the examples at http://davidwalsh.name/php-ternary-examples and this seems correct as far as I can see from the examples. 我正在http://davidwalsh.name/php-ternary-examples上查看示例,就我从示例中看到的来看,这似乎是正确的。 Why does it always return false? 为什么总是返回false?

You may try to simple return the $_SESSION['p_logged_in'] value :- 您可以尝试简单地return $_SESSION['p_logged_in']值:-

function session_active()
{
  return  (bool)$_SESSION['p_logged_in'];
}

php isnt ruby, you have to return that value from the ternary. php不是ruby,您必须从三进制返回该值。

to elaborate in more detail... 详细说明...

function session_active()
{
  return ($_SESSION['p_logged_in'] ? true : false);
}

Try this: 尝试这个:

function session_active() {
   return (isset($_SESSION['p_logged_in'])) ? true : false;
}

to correct your logic add return in front of your statment 更正您的逻辑,在陈述前添加return
to simplify it do: return (bool)$_SESSION['p_logged_in']; 为了简化它: return (bool)$_SESSION['p_logged_in'];

$_SESSION['p_logged_in'] === true$_SESSION['p_logged_in'] != null之间有区别,通过返回$ _SESSION ['p_logged_in']可能会超出其测试范围。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM