批改状态:未批改
老师批语:
这节学习了PHP变量类型与转换,查询与检测,还是非常简单的。
/*变量类型查询,设置与检测
1.类型查询:
gettype($var)
2。类型检测:
is_interger(),是否为数字
is_float(),是否为浮点 double和float同义
is_string(),是否为字符串
is_bool();是否为布尔型
is_array(),是否为数组
is_object,是否为对象
is_null,是否为为空
is_resource()是否为为资源类型
is_numeric 是否为数字或数字字符串
3。类型转换:
强制转换:(int)$var,(string)$var
临时转换(值转换类型不变):intval(),floatval(),strval(),var是value
永久转换:settype($var,类型标识符)
*/
<?php
echo "<h2>变量类型与转换</h2>";
echo "<hr>";
$age=30;
$salary=10000;
$name='sam xu';
$isMarried=true;
echo $name."的年龄是:".$age.',工资是:'.$salary.'是否已婚:'.$isMarried;
echo "<br>";
print($age);
print "<br>";
var_dump($age);
echo "<hr>";
//复合类型:多值变量,包括数组和对象二种
//print_r()或var_dump
//数组输出:
$books=[1,2,3,4,'5万'];
print_r($books);
print "<br>";
var_dump($books);
//对象输出
$student = new stdClass();
$student->name='张三';
$student->age='36';
$student->manny='1000万';
echo "<hr>";
//print($student);
print_r($student);
print "<br>";
var_dump($student);
echo "<hr>";
//特殊类型:资源类型,null
$file=fopen('index.php', 'r') or die('打开失败');
echo fread($file, filesize('index.php'));
fclose($file);
$price=null;
echo '$price 是'.$price;
/*变量类型查询,设置与检测
1.类型查询:
gettype($var)
2。类型检测:
is_interger(),是否为数字
is_float(),是否为浮点 double和float同义
is_string(),是否为字符串
is_bool();是否为布尔型
is_array(),是否为数组
is_object,是否为对象
is_null,是否为为空
is_resource()是否为为资源类型
is_numeric 是否为数字或数字字符串
3。类型转换:
强制转换:(int)$var,(string)$var
临时转换(值转换类型不变):intval(),floatval(),strval(),var是value
永久转换:settype($var,类型标识符)
*/
echo "<hr>";
$price=100.25;
echo gettype($price);
echo "<hr>";
echo (int)$price;//强制转换
echo "<hr>";
echo $price;//查看原始数据,仍是浮点型,并无变化
echo "<hr>";
echo gettype($price);//原始类型仍为double,并未发生变化
echo "<hr>";
echo intval($price);//临时转换,原始数据不发生变化
echo "<hr>";
settype($price,'integer');//永久转换,返回布尔值
echo $price; //变成100
echo "<hr>";
echo gettype($price);//类型变成了integer
echo '<hr>';
echo is_numeric($price) ? 'integer' : 'double';//此时类型是integer
echo '<hr>';
//is_numeric 是否为数字或数字字符串
var_dump(is_numeric(100));
var_dump(is_numeric(100.23));
var_dump(is_numeric('100.23'));
var_dump(is_numeric('100ok'));
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号