PHP知识点大全(五)

简介: 教程来源 https://oieaw.cn/sheyinggoutu.html 本文系统讲解PHP核心知识:错误/异常处理(自定义处理器、全局捕获)、面向对象编程(类、继承、多态、命名空间、Trait)、以及PHP 7/8新特性(类型声明、命名参数、匹配表达式、属性提升等),覆盖开发必备技能。

十二、错误与异常处理

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

相关文章
|
13天前
|
人工智能 JSON 机器人
让龙虾成为你的“公众号分身” | 阿里云服务器玩Openclaw
本文带你零成本玩转OpenClaw:学生认证白嫖6个月阿里云服务器,手把手配置飞书机器人、接入免费/高性价比AI模型(NVIDIA/通义),并打造微信公众号“全自动分身”——实时抓热榜、AI选题拆解、一键发布草稿,5分钟完成热点→文章全流程!
11452 124
让龙虾成为你的“公众号分身” | 阿里云服务器玩Openclaw
|
2天前
|
人工智能 JSON 监控
Claude Code 源码泄露:一份价值亿元的 AI 工程公开课
我以为顶级 AI 产品的护城河是模型。读完这 51.2 万行泄露的源码,我发现自己错了。
3453 8
|
1天前
|
人工智能 数据可视化 安全
王炸组合!阿里云 OpenClaw X 飞书 CLI,开启 Agent 基建狂潮!(附带免费使用6个月服务器)
本文详解如何用阿里云Lighthouse一键部署OpenClaw,结合飞书CLI等工具,让AI真正“动手”——自动群发、生成科研日报、整理知识库。核心理念:未来软件应为AI而生,CLI即AI的“手脚”,实现高效、安全、可控的智能自动化。
1324 2
王炸组合!阿里云 OpenClaw X 飞书 CLI,开启 Agent 基建狂潮!(附带免费使用6个月服务器)
|
12天前
|
人工智能 IDE API
2026年国内 Codex 安装教程和使用教程:GPT-5.4 完整指南
Codex已进化为AI编程智能体,不仅能补全代码,更能理解项目、自动重构、执行任务。本文详解国内安装、GPT-5.4接入、cc-switch中转配置及实战开发流程,助你从零掌握“描述需求→AI实现”的新一代工程范式。(239字)
7457 139
|
2天前
|
云安全 供应链 安全
Axios投毒事件:阿里云安全复盘分析与关键防护建议
阿里云云安全中心和云防火墙第一时间响应
1143 0
|
3天前
|
人工智能 自然语言处理 数据挖掘
零基础30分钟搞定 Claude Code,这一步90%的人直接跳过了
本文直击Claude Code使用痛点,提供零基础30分钟上手指南:强调必须配置“工作上下文”(about-me.md+anti-ai-style.md)、采用Cowork/Code模式、建立标准文件结构、用提问式提示词驱动AI理解→规划→执行。附可复制模板与真实项目启动法,助你将Claude从聊天工具升级为高效执行系统。
|
2天前
|
人工智能 定位技术
Claude Code源码泄露:8大隐藏功能曝光
2026年3月,Anthropic因配置失误致Claude Code超51万行源码泄露,意外促成“被动开源”。代码中藏有8大未发布功能,揭示其向“超级智能体”演进的完整蓝图,引发AI编程领域震动。(239字)
2148 9
|
11天前
|
人工智能 并行计算 Linux
本地私有化AI助手搭建指南:Ollama+Qwen3.5-27B+OpenClaw阿里云/本地部署流程
本文提供的全流程方案,从Ollama安装、Qwen3.5-27B部署,到OpenClaw全平台安装与模型对接,再到RTX 4090专属优化,覆盖了搭建过程的每一个关键环节,所有代码命令可直接复制执行。使用过程中,建议优先使用本地模型保障隐私,按需切换云端模型补充功能,同时注重显卡温度与显存占用监控,确保系统稳定运行。
2548 9