数据类型强制转换
<?php
header("content-type:text/html,charset-utf8");
//强制转换
//临时转换
// (string) strval() 两种方法临时转换
$var = 123;
$var = 12.3;
$var = true;
$var = false;
$var = NULL;
$var = array(12, 3, 4);
// $var = new stdClass;
$var = fopen('5-test.php', 'r');
$res = (string)$var;
var_dump($res);
echo "<hr>";
$var = true;
var_dump(strval($var));
echo "<hr>";
$str = 123; // integer
$str = 12.3; // double
$str = true; // boolean
$str = NULL; // NULL
$str = array(); // array
$str = new stdClass; // object
echo gettype($str); // 获取变量的数据类型
echo "<hr>";
//设置变量类型,永久转换
$var = 123;
settype($var, 'object');
foreach ($var as $key => $value) {
echo $value . "<hr>";
} // 遍历对象
$var = "123";
settype($var, 'integer');
var_dump($var);
字符串相关数据类型转换
<?php
header("content-type:text/html,charset=utf8");
echo 1 + "3lzq";
echo "<br>";
$arr = 1.2 + "3asd";
var_dump($arr);
echo "<br>";
echo 2 + "2e2"; // 2*10的2次方
echo "<br>";
echo 2 + "true" . "<br>"; // 0
echo 1 + "false" . "<br>"; // 0
echo 2 + "false" . "<br>";
//字符串转换成布尔类型的规律,空字符串或者是字符串"","0"->false;
$res = ""; //->false,空字符串
$res = " "; //->true
$res = "0"; //->false
$res = "0.0"; //->true
$res = "false"; //->true
$res = 0; //->false
$res = NULL; //->false
$res = array(); //->false
if ($res) {
echo "我是真的";
} else {
echo "我是假的";
}