Rumah  >  Artikel  >  php变量类型与转换

php变量类型与转换

无忌哥哥
无忌哥哥asal
2018-06-27 17:40:572459semak imbas

echo &#39;<h3>2.变量类型与转换</h3>&#39;;
echo &#39;<hr color="green">&#39;;

//标量:单值变量,包括整型,浮点,字符串,布尔四种

$age = 30; //1整型 integer
$salary = 1234.56; //2.浮点 float
$name = &#39;peter&#39;; //3 字符串
$isMarried = true;  //4. 布尔型,true真,false假

//标量输出echo,print或var_dump()可查看类型和值

echo $name.&#39;的年龄是:&#39;.$age.&#39;,工资是:&#39;.$salary.&#39;,是否已婚:&#39;.$isMarried;
echo &#39;<br>&#39;;
print $name; print &#39;<br>&#39;;
var_dump($name);
echo &#39;<hr color="red">&#39;;

//复合类型: 多值变量,包括数组和对象二种

$books = [&#39;php&#39;,&#39;mysql&#39;,&#39;html&#39;,&#39;css&#39;,&#39;javascript&#39;]; //数组
$student = new stdClass(); //创建空对象$student
$student->name = &#39;王二小&#39;;  //添加属性name
$student->course = &#39;php&#39;;  //添加属性course
$student->grade = 80;     //添加属性grade

//复合变量输出: print_r()或var_dump()

echo &#39;<pre class="brush:php;toolbar:false">&#39;; //格式化输出结果
print_r($books);
print_r($student);
var_dump($books);
var_dump($student);
echo &#39;<hr color="red">&#39;;

//特殊类型:资源类型,null

$file = fopen(&#39;demo.php&#39;,&#39;r&#39;) or die(&#39;打开失败&#39;);
echo fread($file, filesize(&#39;demo.php&#39;));
fclose($file);

$price = null;

echo '$price is '.$price;

/**

 * 变量类型查询,设置与检测

 * 1.类型查询:

 * gettype($var)

 * 2.类型检测:

 * 2.1: is_integer(),

 * 2.2: is_float(),

 * 2.3: is_string(),

 * 2.4: is_bool(),

 *       2.5: is_array(),

 *       2.6: is_object(),

 *       2.7: is_null(),

 *       2.8: is_resource(),

 *       2.9: is_numeric()...

 * 3.类型转换:

 * 3.1: 强制转换: (int)$val,(string)$val...

 * 3.2: 临时转换(值转换类型不变):intval(),floatval(),strval(),val是value

 *  3.3: 永久转换:settype($var,类型标识符)

 */

$price = 186.79;
echo gettype($price);  //float/double浮点型,float和double同义
echo &#39;<hr>&#39;;
echo (int)$price;  //强制转为integer,186
echo &#39;<hr>&#39;;
echo $price;  //查看原始数据,仍是浮点型,并无变化
echo &#39;<hr>&#39;;
echo gettype($price);  //原始类型仍为double,并未发生变化
echo &#39;<hr>&#39;;
echo intval($price);  //临时将值转为整型,输出:186
echo &#39;<hr>&#39;;
echo $price; //输出原值,仍为186.79,原值并未发生变化
echo &#39;<hr>&#39;;
settype($price,&#39;integer&#39;);  //永久转为integer,返回布尔值
echo $price;  //查看值:186
echo &#39;<hr>&#39;;
echo gettype($price);  //类型为integer
echo &#39;<hr>&#39;;
echo is_integer($price)? &#39;Integer&#39; : &#39;Double&#39;; //Integer整型
echo &#39;<hr>&#39;;
//is_numeric():判断是否是数字或数字型字符串
var_dump(is_numeric(100));
var_dump(is_numeric(&#39;200&#39;));
var_dump(is_numeric(&#39;200php&#39;));


Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Artikel sebelumnya:php创建变量Artikel seterusnya:php判断变量