以下是專為 PHP 7.4 初學者設計的全面學習文檔,涵蓋基礎語法、細節語法和進階語法,結合 PHP 7.4 新特性與實戰案例,幫助系統掌握 PHP 開發:
為什么特地做7.4的筆記而不做8的?因為公司用的7.4,哈哈
一、基礎語法:構建 PHP 編程基石
1. 變量與數據類型
- 變量聲明:使用 $ 符號聲明,無需提前指定類型。
$name = "John"; // 字符串
$age = 30; // 整數
$salary = 5000.5; // 浮點數
-
數據類型:標量(int, float, string, bool)、復合(array, object)、特殊(resource, NULL)。
-
類型強制轉換:
$num = (int) "123"; // 轉換為整數
$str = (string) 456; // 轉換為字符串
2. 運算符與表達式
-
算術運算符:+, -, *, /, %。
-
比較運算符:==, ===, >, <, <=, >=。
-
邏輯運算符:&&, ||, !。
-
三元運算符:
$status = $isActive ? "Active" : "Inactive";
3. 流程控制
- 條件語句:
if ($age >= 18) {echo "成年人";
} elseif ($age >= 13) {echo "青少年";
} else {echo "兒童";
}
// for 循環
for ($i = 0; $i < 5; $i++) {echo $i;
}// while 循環
$j = 0;
while ($j < 5) {echo $j++;
}
4. 函數基礎
- 自定義函數:
function add($a, $b) {return $a + $b;
}
echo add(3, 5); // 輸出 8
$greet = function($name) {echo "Hello, $name!";
};
$greet("Alice"); // 輸出 Hello, Alice!
二、細節語法:深入 PHP 7.4 特性
1. 類型聲明(PHP 7.4 增強)
- 標量類型聲明:
declare(strict_types=1); // 開啟嚴格模式function multiply(int $a, int $b): int {return $a * $b;
}
echo multiply(3, "4"); // 嚴格模式下報錯
- 聯合類型(PHP 7.4 新增):
function formatValue(int|string $value): string {return "Value: " . $value;
}
echo formatValue(123); // 輸出 Value: 123
2. 箭頭函數(PHP 7.4 新增)
- 簡潔語法:
$numbers = [1, 2, 3, 4];
$squared = array_map(fn($n) => $n ** 2, $numbers);
print_r($squared); // 輸出 Array([0] => 1, [1] =>4, [2] =>9, [3] =>16)
- 自動捕獲父作用域變量:
$factor = 10;
$nums = array_map(fn($n) => $n * $factor, [1, 2, 3]);
print_r($nums); // 輸出 Array([0] =>10, [1] =>20, [2] =>30)
3. 類型屬性(PHP 7.4 新增)
- 類屬性類型聲明:
class User {public int $id;public string $name;protected ?string $email = null;
}$user = new User();
$user->id = 1; // 合法
$user->name = "Bob"; // 合法
$user->email = "bob@example.com"; // 合法
$user->email = null; // 合法(允許 null)
4. 空合并運算符(??)與空合并賦值運算符(??=)
- 空值處理:
$username = $_GET['user'] ?? "Guest"; // 若 $_GET['user'] 不存在,默認 "Guest"
$this->data['comments'] ??= []; // 若 $this->data['comments'] 為 null,賦值為空數組
三、進階語法:提升代碼質量與效率
1. 面向對象編程(OOP)
- 類與對象:
class Car {public string $model;private int $year;public function __construct(string $model, int $year) {$this->model = $model;$this->year = $year;}public function getInfo(): string {return "{$this->model} ({$this->year})";}
}$car = new Car("Toyota", 2020);
echo $car->getInfo(); // 輸出 Toyota (2020)
- 繼承與多態:
class ElectricCar extends Car {public function charge(): void {echo "Charging...";}
}
2. 命名空間與自動加載
- 命名空間聲明:
namespace App\Controllers;class HomeController {// 控制器邏輯
}
- 自動加載(Composer):
{"autoload": {"psr-4": {"App\\": "src/"}}
}
3. 異常處理
- 異常捕獲與拋出:
try {if (!file_exists("data.txt")) {throw new Exception("文件不存在");}
} catch (Exception $e) {echo "錯誤:" . $e->getMessage();
}
4. 文件操作與安全性
- 文件讀寫:
// 讀取文件
$content = file_get_contents("data.txt");// 寫入文件
file_put_contents("log.txt", "日志信息\n", FILE_APPEND);
- 安全防護:
// 輸入過濾
$username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);// 輸出轉義
echo htmlspecialchars($username);
5. 數據庫操作(MySQLi 預處理語句)
- 連接數據庫:
$mysqli = new mysqli("localhost", "user", "pass", "db");
if ($mysqli->connect_error) {die("連接失敗:" . $mysqli->connect_error);
}
- 預處理語句:
$stmt = $mysqli->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->bind_param("ss", $name, $email);
$name = "Alice";
$email = "alice@example.com";
$stmt->execute();
四、PHP 7.4 新特性深度解析
1. 箭頭函數的應用場景
- 數組處理:
$users = [["name" => "John", "age" => 30],["name" => "Jane", "age" => 25]
];$names = array_map(fn($user) => $user['name'], $users);
print_r($names); // 輸出 Array([0] => John, [1] => Jane)
2. 類型屬性的注意事項
- 默認值設置:
class Product {public float $price = 0.0; // 非空類型需設置默認值public ?string $description = null; // 允許 null
}
3. 協變返回與逆變參數(PHP 7.4 新增)
- 協變返回:
interface Animal {public function makeSound(): string;
}class Dog implements Animal {public function makeSound(): string {return "Woof!";}
}class Cat implements Animal {public function makeSound(): string {return "Meow!";}
}function getAnimal(): Animal {return new Dog(); // 協變返回更具體的類型
}
五、學習資源推薦
-
官方文檔:PHP 官方手冊
-
在線教程:PHP 中文網、W3Schools
-
書籍:《PHP 和 MySQL Web 開發》、《PHP: The Right Way》
-
實戰項目:GitHub PHP 項目
六、學習路線建議
-
階段一(基礎):掌握變量、運算符、流程控制、函數。
-
階段二(進階):學習面向對象、命名空間、異常處理。
-
階段三(實戰):結合數據庫操作、文件處理、安全性開發完整項目。
-
階段四(優化):深入 PHP 7.4 新特性,提升代碼效率與可維護性。