Php 为什么简单的| |像if序列一样工作?

Php 为什么简单的| |像if序列一样工作?,php,if-statement,Php,If Statement,在我的上一个项目中,我必须指定一个值,通常我使用以下语句: <?php $true = 1; $false = 0; $hasAccess = $true ? 1 : 0; print $hasAccess; ?> 但这有助于: <?php $true = 1; $false = 0; $hasAccess = $true || $false; print $hasAccess; ?> 为什么? 更新:我知道什么是或/| |

在我的上一个项目中,我必须指定一个值,通常我使用以下语句:

<?php 
  $true = 1;
  $false = 0;
  $hasAccess = $true ? 1 : 0;
  print $hasAccess;
?>

但这有助于:

<?php 
  $true = 1;
  $false = 0;
  $hasAccess = $true || $false;
  print $hasAccess;
?>

为什么?

更新:我知道什么是或/| |以及我对它的期望。但我以前从未见过这种可能性。

因为

$true ? 1 : 0;
计算结果为
1
,因为
$true
为true,并且

$true || $false;

出于同样的原因,也计算为
1

因为0自动转换为(bool)false,而其他任何(bool)true。 所以你的基本意思是:

$hasaccess=true或false

另见:
http://php.net/manual/en/language.operators.logical.php

如果表达式的任一侧为true,则OR将返回true

因为$true=1,所以表达式作为一个整体是真的


基本上你说的是“如果$true为true,或者$false为true,那么$hasAccess为true”

An | | |这是一个or语句,如果其中一个语句的计算结果为true,则返回该语句。 示例:

$bool = true || false;
// $bool = true

$bool = false || true;
// $bool = true

$bool = false || false;
// $bool = false

$bool = false || true || false;
// $bool = true

$bool = false || 1;
// $bool = true

$bool = false || 'test';
// $bool = true

你为什么不写$hasAccess=1呢?看到一个名为
$true
的非布尔变量让我感到不安……PHP手册真的那么没用吗?我问过,因为我没有找到答案(在我的书、手册、www或谷歌中),对给你带来的不便表示歉意。非常感谢所有其他人,他们花了时间,给我一个答案:现在我明白了。有时我看不见树木,看不见森林;)最后一个不是计算为
true