☰分类导航

PHP/数据类型与变量
课程进度 15% · 第4/22章第4/22章 · 标签 1/3
— 1 —

数据类型详解


```php
<?php
// 标量类型
$int = 42; $float = 3.14;
$str = "Hello"; $bool = true;
// 复合类型
$arr = [1, 2, 3];        // 数组
$obj = new stdClass();    // 对象
// 特殊类型
$null = null;             // null
$res = fopen("file","r"); // resource
?>
```
php
1
<?php
2
// 标量类型
3
$int = 42; $float = 3.14;
4
$str = "Hello"; $bool = true;
5
// 复合类型
6
$arr = [1, 2, 3]; // 数组
7
$obj = new stdClass(); // 对象
8
// 特殊类型
9
$null = null; // null
10
$res = fopen("file","r"); // resource
11
?>

变量作用域


```php
<?php
$global = "全局";          // 全局作用域
function test() {
    global $global;       // 访问全局变量
    static $count = 0;    // 静态变量
    $count++; echo $count;
}
?>
```
php
1
<?php
2
$global = "全局"; // 全局作用域
3
function test() {
4
global $global; // 访问全局变量
5
static $count = 0; // 静态变量
6
$count++; echo $count;
7
}
8
?>
— 2 —

类型判断与转换


```php
<?php
is_int(42);      // true
is_string("a");  // true
is_array([1]);   // true
gettype($var);   // 返回类型名
settype($var, "int"); // 设置类型

// 强制转换
$int = (int)"123";
$str = (string)456;
?>
```
php
1
<?php
2
is_int(42); // true
3
is_string("a"); // true
4
is_array([1]); // true
5
gettype($var); // 返回类型名
6
settype($var, "int"); // 设置类型
7
 
8
// 强制转换
9
$int = (int)"123";
10
$str = (string)456;
11
?>
类型作用域globalstatictype hint