以下是专为 PHP 7.4 初学者设计的全面学习文档,涵盖基础语法、细节语法和进阶语法,结合 PHP 7.4 新特性与实战案例,帮助您系统掌握 PHP 开发:
一、基础语法:构建 PHP 编程基石
1. 变量与数据类型
1 2 3
| $name = "John"; $age = 30; $salary = 5000.5;
|
数据类型:标量(int, float, string, bool)、复合(array, object)、特殊(resource, NULL)。
类型强制转换:
1 2
| $num = (int) "123"; $str = (string) 456;
|
2. 运算符与表达式
算术运算符:+, -, *, /, %。
比较运算符:==, ===, >, <, <=, >=。
逻辑运算符:&&, ||, !。
三元运算符:
1
| $status = $isActive ? "Active" : "Inactive";
|
3. 流程控制
1 2 3 4 5 6 7
| if ($age >= 18) { echo "成年人"; } elseif ($age >= 13) { echo "青少年"; } else { echo "儿童"; }
|
1 2 3 4 5 6 7 8 9 10
| for ($i = 0; $i < 5; $i++) { echo $i; }
$j = 0; while ($j < 5) { echo $j++; }
|
4. 函数基础
1 2 3 4
| function add($a, $b) { return $a + $b; } echo add(3, 5);
|
1 2 3 4
| $greet = function($name) { echo "Hello, $name!"; }; $greet("Alice");
|
二、细节语法:深入 PHP 7.4 特性
1. 类型声明(PHP 7.4 增强)
1 2 3 4 5 6
| declare(strict_types=1);
function multiply(int $a, int $b): int { return $a * $b; } echo multiply(3, "4");
|
1 2 3 4
| function formatValue(int|string $value): string { return "Value: " . $value; } echo formatValue(123);
|
2. 箭头函数(PHP 7.4 新增)
1 2 3
| $numbers = [1, 2, 3, 4]; $squared = array_map(fn($n) => $n ** 2, $numbers); print_r($squared);
|
1 2 3
| $factor = 10; $nums = array_map(fn($n) => $n * $factor, [1, 2, 3]); print_r($nums);
|
3. 类型属性(PHP 7.4 新增)
1 2 3 4 5 6 7 8 9 10 11
| 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;
|
4. 空合并运算符(??)与空合并赋值运算符(??=)
1 2
| $username = $_GET['user'] ?? "Guest"; $this->data['comments'] ??= [];
|
三、进阶语法:提升代码质量与效率
1. 面向对象编程(OOP)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| 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();
|
1 2 3 4 5
| class ElectricCar extends Car { public function charge(): void { echo "Charging..."; } }
|
2. 命名空间与自动加载
1 2 3 4 5
| namespace App\Controllers;
class HomeController { }
|
1 2 3 4 5 6 7
| { "autoload": { "psr-4": { "App\\": "src/" } } }
|
3. 异常处理
1 2 3 4 5 6 7
| try { if (!file_exists("data.txt")) { throw new Exception("文件不存在"); } } catch (Exception $e) { echo "错误:" . $e->getMessage(); }
|
4. 文件操作与安全性
1 2 3 4 5
| $content = file_get_contents("data.txt");
file_put_contents("log.txt", "日志信息\n", FILE_APPEND);
|
1 2 3 4 5
| $username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
echo htmlspecialchars($username);
|
5. 数据库操作(MySQLi 预处理语句)
1 2 3 4
| $mysqli = new mysqli("localhost", "user", "pass", "db"); if ($mysqli->connect_error) { die("连接失败:" . $mysqli->connect_error); }
|
1 2 3 4 5
| $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. 箭头函数的应用场景
1 2 3 4 5 6 7
| $users = [ ["name" => "John", "age" => 30], ["name" => "Jane", "age" => 25] ];
$names = array_map(fn($user) => $user['name'], $users); print_r($names);
|
2. 类型属性的注意事项
1 2 3 4
| class Product { public float $price = 0.0; public ?string $description = null; }
|
3. 协变返回与逆变参数(PHP 7.4 新增)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| 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 新特性,提升代码效率与可维护性。