数据类型在php并不像java中那详细那么多种类型,下面我来给各位同学介绍php 数据类型的一些基础知道,各位同学可参考.
PHP 数据类型
PHP 支持八种原始类型(type).
四种标量类型:
1.string(字符串)
2.integer(整型)
3.float(浮点型,也作 double )
4.boolean(布尔型)
两种复合类型:
1.array(数组)
2.object(对象)
两种特殊类型:
1.resource(资源)
2.NULL(空)
查看变量类型
通过 gettype() 函数可以方便的查看某个变量的类型:
- <?php
- $bool = TRUE; // 布尔型
- $str = "foo"; // 字符串
- $int = 12; // 整型
- echo gettype($bool); // 输出 boolean
- echo gettype($str); // 输出 string
- echo gettype($int); // 输出 integer
- ?>
判断变量类型
如果想通过判断变量类型来可以使用 is_type 函数:
- <?php
- $var_int = 12;
- // 如果 $var_int 是 int 类型,这进行加法
- if (is_int($var_int)) {
- $var_int = $var_int+4;
- }
- echo $var_int; // 输出 16
- ?>
以上基本就是PHP数据类型的基本内容,大家如果想了解具体每个数据类型的用法,可以查阅PHP手册,里面有详细的说明.
数据类型转换
PHP数据类型有三种转换方式:
•在要转换的变量之前加上用括号括起来的目标类型
•使用3个具体类型的转换函数,intval()、floatval()、strval()
•使用通用类型转换函数settype(mixed var,string type)
第一种转换方式: (int) (bool) (float) (string) (array) (object)
- •<?php
- •$num1=3.14;
- •$num2=(int)$num1;
- •var_dump($num1); //输出float(3.14)
- •var_dump($num2); //输出int(3)
- •?>
第二种转换方式: intval() floatval() strval()
- •<?php
- •$str="123.9abc";
- •$int=intval($str); //转换后数值:123
- •$float=floatval($str); //转换后数值:123.9
- •$str=strval($float); //转换后字符串:"123.9"
- •?>
第三种转换方式: settype();
- •<?php
- •$num4=12.8;
- •$flg=settype($num4,"int");
- •var_dump($flg); //输出bool(true)
- •var_dump($num4); //输出int(12)
- •?>
PHP数据类型隐性转换的陷阱,我这里说的是php5+上跑的,php4的请飘过.先把错误报告打开,以防看不到错误信息
- <?php
- error_reporting(E_ALL);
- ini_set('display_errors', true);
- ?>
根据php manual 中 http://www.php.net/manual/zh/language.operators.comparison.php
“Comparison Operators” 一章的说明可知,number 和string进行比较的时候,会先将string类型首先转化为number,然后再进行比较操作.
1.类型自动转换为数组
当我们把一个非数组的变量当做数组来调用的时候,该变量在调用时数据类型临时自动转换成数组.
实例代码如下:
- <?php
- $str = 'string';
- var_dump($str['aaa']); // string(1) "s"
- var_dump($str); // string(6) "string"
- if($str['aaa'] === $str[0]) {
- print "===";
- }
- ?>
如下例子可以明显的看出下标类型自动转换在发生.
- <?php
- $link = '<a href="http://yulans.cn">yulans</a>';
- $key = '1-10';
- echo "$link[$key]n"; // 同 $link[1]
- echo "{$link[$key]}n"; // 同 $link[1]
- //echo "$link['$key']n"; // 报错
- echo "{$link['$key']}n"; // 同 $link[0]
- ?>
这里字符串在 var_dump($str['aaa']) 被临时转换成了数组 array('s','t','r','i', 'n','g'),而用关联数组方式
$str['aaa']读取索引数组的值,关联数组的下标'aaa'将被转换成整形下标,因而在这里的$str['aaa']全等于$str[0].其他数据类型隐性转换成数组也隐藏有陷阱,一般都不是报出undefined index错误.
举例如下代码:
- <?php
- /**
- * 测试变量隐性转换成数组
- *
- * @param mixed $param
- */
- function test2Arr($param) {
- var_dump($param['abc']);
- }
- test2Arr(false); // NULL
- test2Arr(123); // NULL
- test2Arr(123.456); // NULL
- test2Arr('string'); // string(1) "s"
- test2Arr(array('abc'=>'text')); // string(4) text
- test2Arr(new ArrayObject()); // Notice: undefined index: abc
- ?>
解决办法:
函数参数数据类型是数组的时候,防止用户输入字符串导致错误,如下例子,当添加用户的时候,我们要求用户必须输入用户名.没有哪个SB把要求是数组的参数传入字符串,但是防人之心不可无,说不定我连续工作超过十几个小时后一不小心就成那个SB了,又或许某人想绕过代码执行操作.
- <?php
- /**
- * 添加用户(错误的写法)
- *
- * @param array $user
- */
- function addUser($user) {
- if(emptyempty($user['name'])) { // 这里当输入类型是不为空的字符串的时候会出错,
- echo "用户名必填n";
- return false;
- }
- // do sth.
- echo "测试n";
- return true;
- }
- /**
- * 添加用户(正确的写法)
- *
- * @param array $user
- */
- function addUser2($user) {
- if(!is_array($user) || emptyempty($user['name'])) {
- echo "用户名必填n";
- return false;
- }
- // do sth.
- echo "测试n";
- return true;
- }
- $user = 'xiaoxiao';
- addUser($user);
- addUser2($user);
- ?>
2.纯数字字符串比较时自动转换成整形超过范围时发生溢出
- <?php
- $x1 = '111111111111111111';
- $x2 = '111111111111111112';
- echo ($x1 === $x2) ? "true" : "false"; // false 如我们所愿,这两个字符串确实不一样.
- echo ($x1 == $x2) ? "true" : "false"; // true 这里被偷偷的转换类型了,
- // 成了 echo (intval($x1) == intval($x2)) ? "true" : "false"; 整形溢出
- ?>
3、整形和字符串比较时数据类型隐性转换有可能发生问题
- <?php
- $number = 0;
- $string = 'text';
- if($number == $string) {
- print "true";
- } else {
- print "false";
- }
- ?>
很遗憾这里输出的是 true,我们知道 $number === $string 肯定是false,手册上说 === 是比较值&&数据类型,而用 == 只是比较值,$number == $string 这里不是比较值吗? '0' 和 'text' 明显不一样啊.小心了,这里的$string是先被秘密转成和$number一样的整形再比较的,$number == (int)$string的确是true
4. in_array 小陷阱
因为in_array会将0 和's' 进行比较,0是number类型,'s'是string类型, 's'转化为number的结果为0,而0 == 0 的结果是true,所以in_array(0, array('s', 'ss'))的结果也是true.如果把in_array 的第三个参数strict设置为 true,比较的时候 就会判断值和类型是否都相当.如果都相当的话,才会返回true,否则返回false.
波比源码 » Php入门教程之PHP 数据类型用法详解
buy levofloxacin pills order levaquin for sale
avodart 0.5mg canada celebrex 200mg over the counter ondansetron 8mg ca
spironolactone tablet generic propecia 1mg fluconazole brand
ampicillin over the counter trimethoprim over the counter brand erythromycin 250mg
order fildena 50mg online cheap sildenafil 50mg price robaxin pill
suhagra for sale order sildalis for sale order estrace 2mg online cheap
lamictal online order retin cream sale retin medication
buy tadalis 10mg generic order tadacip online diclofenac pill
buy isotretinoin 20mg sale buy zithromax 250mg online cheap cost zithromax
tadalafil 20mg price best pills for ed sildenafil tablets
tadalafil 10mg sans ordonnance en pharmacie acheter 20mg gГ©nГ©rique cialis en france viagra pour homme
prednisone 20mg cost sildenafil canada real viagra 100mg
cialis 5mg generika original cialis 20mg rezeptfrei sicher kaufen sildenafil 50mg kaufen generika
generic accutane 10mg generic amoxicillin 250mg ivermectin generic name
modafinil 100mg us buy diamox sale diamox 250mg oral
ramipril canada clobetasol oral order azelastine 10 ml without prescription
buspirone 10mg price phenytoin 100 mg canada buy oxybutynin generic
terazosin pill buy arava 10mg pills purchase sulfasalazine generic
purchase isosorbide generic buy azathioprine 50mg pills order micardis generic
zyban 150mg ca strattera 25mg usa buy seroquel 50mg pills
molnupiravir online buy molnupiravir 200 mg without prescription lansoprazole buy online
purchase tadalafil pill healthy man viagra offer buy sildenafil for sale
buy tadalafil 20mg symmetrel 100 mg pills amantadine medication
naltrexone 50 mg tablet letrozole over the counter purchase abilify generic
order dapsone 100 mg generic avlosulfon cost order aceon pill
buy medroxyprogesterone pills cheap periactin 4 mg buy cyproheptadine 4mg online
order accutane without prescription order accutane 40mg generic deltasone 20mg sale
nootropil 800 mg usa order sildenafil generic buy sildenafil 100mg online
lasix for sale generic furosemide 40mg plaquenil 400mg canada
cialis super active betnovate 20 gm drug buy anafranil sale
buy zyvox 600 mg sale casino moons online casino play blackjack online
omeprazole cheap need help writing a paper jackpot party casino
lopressor sale purchase atenolol for sale vardenafil 10mg tablet
buy custom research paper pay to do my assignment cheap viagra for sale
purchase triamcinolone online buy claritin sale order desloratadine generic
dapoxetine 30mg pill generic dapoxetine 90mg order synthroid 75mcg pills
generic tadalafil 40mg sildenafil 50mg tablets viagra overnight shipping
purchase xenical pills orlistat 120mg ca zovirax cheap
tadalafil 10mg without prescription propranolol us buy clopidogrel 75mg pill
buy allopurinol 300mg without prescription cheap allopurinol 300mg zetia 10mg pill
order lioresal sale oral baclofen 25mg ketorolac canada
buy sumatriptan 50mg pills avodart ca buy dutasteride
zantac 300mg canada buy meloxicam 15mg online cheap buy celecoxib generic
order generic tadalafil 5mg buy generic cialis 20mg ciprofloxacin 1000mg generic
buy diflucan pills brand sildenafil 100mg sildenafil without a doctor’s prescription
tadalafil 10mg oral order sildenafil without prescription viagra 100mg us
cefuroxime 250mg sale cefuroxime sale robaxin brand
slot machine casino online blackjack order generic cialis 10mg
purchase trazodone sale trazodone 100mg cost sildenafil cheap
buy deltasone pills buy isotretinoin sale oral amoxicillin
sildenafil 50mg drug viagra 100mg brand order tadalafil 40mg for sale
play real poker online otc ed pills that work purchase cialis pills
order zithromax 500mg for sale prednisolone cheap order neurontin online cheap
burton brunette provigil 100mg usa order modafinil pill
fildena online sildenafil order rhinocort us
buy retin order tadalafil generic buy avana 100mg without prescription
buy generic biaxin purchase catapres pills meclizine price
write my thesis buy sulfasalazine 500 mg generic purchase sulfasalazine sale
buy asacol 800mg without prescription purchase asacol without prescription avapro 150mg drug
buy diamox online order generic acetazolamide 250 mg azathioprine without prescription
order amoxil 500mg online cheap amoxicillin 250mg cost price of stromectol
priligy 30mg for sale motilium online buy buy motilium 10mg generic
pamelor 25mg brand nortriptyline 25mg sale paxil 10mg cheap
cheap indocin 75mg flomax 0.4mg for sale order generic cenforce 50mg
brand famotidine mirtazapine online order order mirtazapine pill
buy requip 1mg without prescription generic labetalol 100mg trandate buy online
buy esomeprazole 40mg online cheap buy furosemide lasix 100mg generic
order cialis 10mg generic cialis generic top rated ed pills
generic minocycline 50mg purchase hytrin online cheap order terazosin pills
buy zofran for sale zofran price trimethoprim cost
order albuterol for sale cheap levothroid without prescription buy augmentin 375mg without prescription
brand provigil modafinil 200mg pills metoprolol 100mg canada
prednisolone pills buy prednisolone 5mg generic order furosemide for sale
order vibra-tabs without prescription order doxycycline 100mg generic buy zovirax 800mg
order imuran online cheap order imuran pill buy naprosyn 500mg pill