这对我来说似乎是PHP的一个非常神秘的部分,我想知道是否有人可以澄清一下,因为手册中似乎没有包括这一点(或者我在任何地方都找不到它)。
其中的一些东西会返回什么呢?
if($c = mysql_connect($host, $user, $pass)){
echo 'Success';
}else{
echo 'Failure';
}这会因为$c被成功赋值为true或false而总是回显'Success‘吗?我想知道我是否可以这样做,或者我是否必须在前一行上定义$c。
谢谢。
发布于 2011-07-03 08:03:35
PHP是一种“弱类型”语言,这意味着php不需要(也不支持)变量的显式类型声明。
注意consufe或将0 1计算为true/false (布尔值)
以本例为例:
$s = "0"; //String s = '0'
$res = strstr($s,'0'); //Search the character zero into the string $s
if ($res){
echo "Zero found!";
}else{
echo "Zero not found!"
}
//Hey!! Whats up!!?? Zero is not found!这是因为strstr函数的返回值为FALSE,在某些情况下会产生意想不到的结果。
正确的方法是使用Not Identical运算符!==,其中比较value和类型
前面的示例应该是:
$s = "0"; //String s = '0'
$res = strstr($s,'0'); //Search the character zero into the string $s
if ($res !== FALSE){//Check for value AND type
echo "Zero found!";
}else{
echo "Zero not found!"
}
//yeah now it works!因此,在您的情况下,我会将if语句编写为:
if(($c = mysql_connect($host, $user, $pass)) !== FALSE){
echo 'Success';
}else{
echo 'Failure';
}https://stackoverflow.com/questions/6560163
复制相似问题