echo '<h3>2.变量类型与转换</h3>'; echo '<hr color="green">';
//Scalar: single-valued variable, including integer, floating point, string, and Boolean.
$age = 30; //1整型 integer $salary = 1234.56; //2.浮点 float $name = 'peter'; //3 字符串 $isMarried = true; //4. 布尔型,true真,false假
//Scalar output echo, print or var_dump() can view the type and value
echo $name.'的年龄是:'.$age.',工资是:'.$salary.',是否已婚:'.$isMarried; echo '<br>'; print $name; print '<br>'; var_dump($name); echo '<hr color="red">';
//Composite type: multi-valued variables, including arrays and objects
$books = ['php','mysql','html','css','javascript']; //数组 $student = new stdClass(); //创建空对象$student $student->name = '王二小'; //添加属性name $student->course = 'php'; //添加属性course $student->grade = 80; //添加属性grade
//Composite variable output: print_r() or var_dump()
echo '<pre class="brush:php;toolbar:false">'; //格式化输出结果 print_r($books); print_r($student); var_dump($books); var_dump($student); echo '<hr color="red">';
//Special Type: resource type, null
$file = fopen('demo.php','r') or die('打开失败'); echo fread($file, filesize('demo.php')); fclose($file);
$price = null;
echo '$price is '.$price;
/**
* Variable type query, setting and detection
* 1. Type query:
* gettype($var)
* 2. Type detection:
* 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. Type conversion:
* 3.1: Force conversion: (int)$val,( string)$val...
* 3.2: Temporary conversion (the value conversion type remains unchanged): intval(), floatval(), strval(), val is value
* 3.3: Permanent conversion: settype($var, type identifier)
* /
$price = 186.79; echo gettype($price); //float/double浮点型,float和double同义 echo '<hr>'; echo (int)$price; //强制转为integer,186 echo '<hr>'; echo $price; //查看原始数据,仍是浮点型,并无变化 echo '<hr>'; echo gettype($price); //原始类型仍为double,并未发生变化 echo '<hr>'; echo intval($price); //临时将值转为整型,输出:186 echo '<hr>'; echo $price; //输出原值,仍为186.79,原值并未发生变化 echo '<hr>'; settype($price,'integer'); //永久转为integer,返回布尔值 echo $price; //查看值:186 echo '<hr>'; echo gettype($price); //类型为integer echo '<hr>'; echo is_integer($price)? 'Integer' : 'Double'; //Integer整型 echo '<hr>'; //is_numeric():判断是否是数字或数字型字符串 var_dump(is_numeric(100)); var_dump(is_numeric('200')); var_dump(is_numeric('200php'));