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

相关文章
|
8月前
|
存储
阿里云企业网盘收费标准:2026年最新收费价格6元1个月、169元一年,看完再买不踩坑!
阿里云盘企业版2026年最新收费标准:https://t.aliyun.com/U/wbANEa 云盘企业版官方报价5人500GB仅169.9元/年,含存储、外网流出流量、智能媒体处理等全功能;支持5–1000人、500GB–100TB共13档套餐,包年预付费,无隐性费用。优惠期免收外网流出费。
|
3月前
|
人工智能 JSON 前端开发
从零用 Spring AI 搭建 RAG + Tool Calling 岗位分析系统:全流程实战与踩坑记录
本文记录使用Spring AI Alibaba+通义千问,从零构建“岗位分析+转岗建议”RAG+Tool Calling系统全过程:涵盖流式输出、结构化响应、知识库检索、薪资工具调用与Advisor编排,并详述5大实战坑点及解决方案,践行“AI不裁员,只赋能”的人文技术理念。
|
2月前
|
人工智能 缓存 移动开发
秒悟是什么?阿里云秒悟(Meoo)AI创作平台:一句话生成网页、PPT和数据可视化
秒悟(Meoo)是阿里云推出的云端AI创作平台,支持一句话生成网页、PPT、数据可视化等内容,无需编程基础。提供免费版及Pro/Max订阅版,最低9.9元/月,含积分额度与多模型调用能力。
472 0
|
9月前
|
XML 前端开发 开发者
CSS学习知识点大全(一)
教程来源 https://app-a7illrp9pngh.appmiaoda.com/ 梳理CSS核心知识:从基础语法、四大引入方式,到选择器(基础/组合/属性/伪类/伪元素)及优先级规则;详解盒模型(标准/怪异)、属性设置与外边距折叠。助力新手构建完整体系,也为开发者提供深度参考。
|
3月前
|
SQL 安全 API
OpenClaw 2.0 便捷安装来了,免费领 Agent 安全用数套件 + 100 万免费 Token 一键到位
阿里云推出AIDBS Agent安全用数套件,适配OpenClaw 2.0,预装DataGuard(行为防护)、DataGateway(数据通道安全)及四大专业SKILL(分析/知识/运维/问答),公测免费,赠100万Qwen3.8-Max Token。
318 0
【B2B 电商干货】1688 店铺流量充足转化率低迷?8 大模块拆解客户流失问题及落地优化方案
本文针对1688 B端商家“高曝光、低转化”痛点,系统拆解客户流失的5大核心节点,从流量精准度、页面视觉、信任体系、客服运营等8大维度,提供可落地的优化策略与10分钟日常自检清单,助力商家提升转化效率。
|
6月前
|
SQL 人工智能 机器人
Agent 是什么,怎么用——从概念到企业落地的完整拆解
AI Agent 怎么用?本文系统拆解 Agent 的核心架构(规划、记忆、工具调用、反思)、典型场景(数据分析、信息搜集、智能路由、代码调试)和企业落地四阶段路径,并客观评估当前 Agent 技术的能力上限与局限。
|
12月前
|
安全 Java API
Java日期处理完全指南(新手也能轻松掌握的Java时间格式化与日期API教程)
教程来源https://www.vpshk.cn/本文介绍Java 8引入的java.time包,详解LocalDateTime、LocalDate等类的使用,涵盖获取当前时间、格式化、解析字符串及日期运算,助你轻松掌握现代Java日期处理方法,适合初学者快速上手。
|
7月前
|
移动开发 前端开发 JavaScript
前端组件库——Plyr 知识点大全(一)
教程来源 https://bncne.cn Plyr 是一款轻量(仅5KB)、无依赖的 HTML5 媒体播放器,支持视频、音频及 YouTube/Vimeo 嵌入。它提供统一美观的 UI、卓越可访问性与跨浏览器一致性,开箱即用,兼容 Vue/React,是替代原生播放器的理想选择。
|
8月前
|
资源调度 前端开发 Android开发
前端组件库——NativeBase知识点大全
教程来源 https://yyvgt.cn NativeBase是2016年推出的React Native跨平台UI库,支持Android、iOS与Web,以统一设计系统为核心。v3版强化可访问性、响应式布局、主题定制与多端一致性,新项目推荐使用;追求极致性能可关注其演进产物gluestack-ui。

热门文章

最新文章