十二、错误与异常处理
12.1 错误处理
<?php
// 错误报告级别
error_reporting(E_ALL); // 所有错误
error_reporting(E_ALL & ~E_WARNING); // 除警告外所有
error_reporting(E_ERROR | E_WARNING); // 只显示错误和警告
// 显示错误
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
// 日志错误
ini_set('log_errors', 1);
ini_set('error_log', '/path/to/error.log');
// 自定义错误处理函数
function customError($errno, $errstr, $errfile, $errline) {
echo "错误级别:{$errno}<br>";
echo "错误信息:{$errstr}<br>";
echo "文件:{$errfile}<br>";
echo "行号:{$errline}<br>";
// 返回true表示已处理,不调用PHP内置处理器
return true;
}
set_error_handler("customError");
// 触发错误
trigger_error("自定义错误", E_USER_WARNING);
// 恢复错误处理器
restore_error_handler();
12.2 异常处理
<?php
// 自定义异常类
class ValidationException extends Exception {
private $errors;
public function __construct($errors, $message = "验证失败", $code = 0) {
parent::__construct($message, $code);
$this->errors = $errors;
}
public function getErrors() {
return $this->errors;
}
}
// 抛出异常
function divide($a, $b) {
if ($b == 0) {
throw new InvalidArgumentException("除数不能为零");
}
return $a / $b;
}
// 捕获异常
try {
$result = divide(10, 0);
echo $result;
} catch (InvalidArgumentException $e) {
echo "错误:" . $e->getMessage();
} catch (Exception $e) {
echo "其他错误:" . $e->getMessage();
} finally {
echo "无论是否异常都会执行";
}
// 异常处理最佳实践
function validateUser($data) {
$errors = [];
if (empty($data['name'])) {
$errors['name'] = "姓名不能为空";
}
if (!filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
$errors['email'] = "邮箱格式错误";
}
if (!empty($errors)) {
throw new ValidationException($errors);
}
return true;
}
// 设置全局异常处理器
function globalExceptionHandler($e) {
echo "未捕获的异常:" . $e->getMessage();
// 记录日志
error_log($e->getTraceAsString());
}
set_exception_handler("globalExceptionHandler");
十三、面向对象编程(OOP)
13.1 类与对象
<?php
// 类定义
class Person {
// 属性(成员变量)
private $name;
private $age;
// 常量
const SPECIES = "人类";
// 静态属性
public static $count = 0;
// 构造函数
public function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
self::$count++;
}
// 析构函数
public function __destruct() {
self::$count--;
}
// 方法
public function getName() {
return $this->name;
}
public function setName($name) {
$this->name = $name;
}
// 静态方法
public static function getCount() {
return self::$count;
}
// 魔术方法
public function __toString() {
return "{$this->name} ({$this->age}岁)";
}
public function __call($name, $arguments) {
echo "方法 {$name} 不存在";
}
public static function __callStatic($name, $arguments) {
echo "静态方法 {$name} 不存在";
}
public function __get($name) {
if (property_exists($this, $name)) {
return $this->$name;
}
return null;
}
public function __set($name, $value) {
$this->$name = $value;
}
public function __isset($name) {
return isset($this->$name);
}
public function __unset($name) {
unset($this->$name);
}
}
// 创建对象
$person = new Person("张三", 25);
echo $person->getName(); // 张三
echo Person::getCount(); // 1
echo Person::SPECIES; // 人类
echo $person; // 调用__toString()
// 克隆对象
$person2 = clone $person;
// 对象比较
if ($person == $person2) {
echo "相等";
}
if ($person === $person2) {
echo "同一个对象";
}
13.2 继承与多态
<?php
// 父类
class Animal {
protected $name;
public function __construct($name) {
$this->name = $name;
}
public function speak() {
return "动物发出声音";
}
final public function breathe() {
return "呼吸";
}
}
// 子类
class Dog extends Animal {
public function speak() {
return "汪汪汪";
}
public function wagTail() {
return "摇尾巴";
}
}
class Cat extends Animal {
public function speak() {
return "喵喵喵";
}
}
// 多态
function makeSound(Animal $animal) {
echo $animal->speak();
}
$dog = new Dog("旺财");
$cat = new Cat("咪咪");
makeSound($dog); // 汪汪汪
makeSound($cat); // 喵喵喵
// 抽象类
abstract class Shape {
protected $color;
abstract public function getArea();
public function setColor($color) {
$this->color = $color;
}
}
class Circle extends Shape {
private $radius;
public function __construct($radius) {
$this->radius = $radius;
}
public function getArea() {
return pi() * $this->radius * $this->radius;
}
}
// 接口
interface Drawable {
public function draw();
}
interface Resizable {
public function resize($percent);
}
class Rectangle implements Drawable, Resizable {
private $width;
private $height;
public function draw() {
echo "绘制矩形";
}
public function resize($percent) {
$this->width *= $percent;
$this->height *= $percent;
}
}
13.3 命名空间
<?php
// namespace/User.php
namespace App\Models;
class User {
public function __construct() {
echo "User类";
}
}
// namespace/Helper.php
namespace App\Helpers;
function formatDate($date) {
return date('Y-m-d', strtotime($date));
}
// index.php
use App\Models\User;
use function App\Helpers\formatDate;
use const App\Config\VERSION;
$user = new User();
echo formatDate('2024-01-01');
// 别名
use App\Models\User as UserModel;
$user = new UserModel();
// 全局命名空间
$date = new \DateTime();
// 命名空间分组
use App\{Models\User, Helpers\formatDate};
13.4 Trait
<?php
// Trait定义
trait Logger {
protected $logFile = 'app.log';
public function log($message) {
echo "日志:" . $message . "\n";
file_put_contents($this->logFile, $message . "\n", FILE_APPEND);
}
abstract public function getName();
}
trait Timestamp {
public function getCreatedAt() {
return date('Y-m-d H:i:s');
}
}
// 使用Trait
class User {
use Logger, Timestamp;
private $name;
public function __construct($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
public function save() {
$this->log("用户 {$this->name} 已保存");
}
}
$user = new User("张三");
$user->save();
echo $user->getCreatedAt();
// Trait冲突解决
trait A {
public function hello() {
echo "Hello from A";
}
}
trait B {
public function hello() {
echo "Hello from B";
}
}
class MyClass {
use A, B {
A::hello insteadof B; // 使用A的hello
B::hello as helloB; // 别名
}
}
十四、PHP新特性
14.1 PHP 7.x 新特性
<?php
// 1. 标量类型声明
function sum(int $a, int $b): int {
return $a + $b;
}
// 2. 返回类型声明
function getValue(): string {
return "Hello";
}
// 3. null合并运算符
$username = $_GET['user'] ?? '匿名';
// 4. 太空船运算符
$result = $a <=> $b;
// 5. 数组常量
define('COLORS', ['red', 'green', 'blue']);
// 6. 匿名类
$obj = new class {
public function hello() {
return "Hello";
}
};
// 7. use批量声明
use Some\Namespace\{ClassA, ClassB, ClassC};
// 8. intdiv函数
echo intdiv(10, 3); // 3
// 9. 随机字符串生成
$bytes = random_bytes(16);
$int = random_int(1, 100);
14.2 PHP 8.x 新特性
<?php
// 1. 命名参数
function createUser($name, $age, $email) {
// ...
}
createUser(name: "张三", age: 25, email: "zhang@example.com");
// 2. 属性注解(Attributes)
#[Route('/api/users', methods: ['GET'])]
function getUsers() {
// ...
}
// 3. 匹配表达式(Match)
$result = match($status) {
200 => "OK",
404 => "Not Found",
500 => "Server Error",
default => "Unknown",
};
// 4. 构造器属性提升
class User {
public function __construct(
private string $name,
private int $age,
private ?string $email = null
) {}
}
// 5. null安全运算符
$city = $user?->address?->city;
// 6. 字符串包含检查
str_contains($haystack, $needle);
str_starts_with($haystack, $needle);
str_ends_with($haystack, $needle);
// 7. 非捕获捕获
try {
// ...
} catch (Exception) {
// 不需要异常变量
}
// 8. 混合类型
function process(mixed $data): mixed {
return $data;
}
// 9. 联合类型
function validate(int|string $input): bool {
return true;
}
// 10. 静态返回类型
class ParentClass {
public static function create(): static {
return new static();
}
}
PHP作为全球最流行的服务器端编程语言之一,以其简单易学、功能强大、生态丰富等优势,成为Web开发的首选语言之一。本文从基础语法到高级特性,从函数数组到面向对象,从数据库操作到新特性,系统性地梳理了PHP的核心知识点。
来源:
https://oieaw.cn/xiangjicanshu.html