超越PHP PHP动态 | 经典文章 | CLASS | 相关下载 | 常见问题 | FORUM | WIKI | 在线手册
Site search:    
<类型整型>
Last updated: Fri, 22 Jun 2007

布尔型

这是最简单的类型。boolean 表达了真值,可以为 TRUEFALSE

注: 布尔类型是 PHP 4 引进的。

语法

要指定一个布尔值,使用关键字 TRUEFALSE。两个都是大小写不敏感的。

<?php
$foo
= True; // assign the value TRUE to $foo
?>

通常你用某些运算符返回 boolean 值,并将其传递给流程控制

// == is an operator which test
// equality and returns a boolean
if ($action == "show_version") {
   echo "The version is 1.23";
}

// this is not necessary...
if ($show_separators == TRUE) {
   echo "<hr>\n";
}

// ...because you can simply type
if ($show_separators) {
   echo "<hr>\n";
}

转换为布尔值

要明示地将一个值转换成 boolean,用 (bool) 或者 (boolean) 来强制转换。但是很多情况下不需要用强制转换,因为当运算符,函数或者流程控制需要一个 boolean 参数时,该值会被自动转换。

参见类型戏法

当转换为 boolean 时,以下值被认为是 FALSE

所有其它值都被认为是 TRUE(包括任何资源)。

警告

-1 和其它非零值(不论正负)一样,被认为是 TRUE

<?php
echo gettype((bool) "");        // bool(false)
echo gettype((bool) 1);        // bool(true)
echo gettype((bool) -2);        // bool(true)
echo gettype((bool) "foo");    // bool(true)
echo gettype((bool) 2.3e5);    // bool(true)
echo gettype((bool) array(12)); // bool(true)
echo gettype((bool) array());  // bool(false)
?>




add a note add a note User Contributed Notes
布尔型
rachel at NO-UBE dot xtreme dot com
30-Apr-2003 12:49
If you aren't sure whether your variable is actually a boolean or not, be very careful with it.  For whatever reason, a true boolean is stored as the number 1, and a false boolean is stored as nothing, null, empty string, or whatnot.  Thus,

$myBool = true ;  print( $myBool ) ;

is indistinguishable from

print( "" ) ;

likewise,

&myBool = false ; print( $myBool ) ;

is indistinguishable from

print( 1 ) ;

In addition to the above warnings about boolean evaluation, note that testing for equality is particularly unintuitive.  In particular, "false" the string will equate to true.  For example,

$myTrueBool = true ;
if( $myTrueBool == "true" ) print("it's true!") ;
if( $myTrueBool == "false" ) print("it's false!") ;
if( $myTrueBool == "mushroom" ) print("it's a mushroom!") ;
if( $myTrueBool == 4 ) print("it's the number 4!") ;

will print out

it's true!
it's false!
it's a mushroom!
it's the number 4!

But if $myTrueBool were false, instead, you'd get nothing at all.  Caveat Usor.

<类型整型>
 Last updated: Fri, 22 Jun 2007
view source | feedback | send page | sitemap | aboutus   
Copyright ® 2002-2003 PHPE.NET. All rights reserved
Last updated:2002-11-22