PHP的进阶用法

3 阅读1分钟

面向对象编程(OOP)示例

类和继承

php
复制编辑
<?php

// 父类
class Animal {
    protected $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function speak() {
        return "Animal makes a sound.";
    }
}

// 子类
class Dog extends Animal {
    public function speak() {
        return $this->name . " says Woof!";
    }
}

$dog = new Dog("Buddy");
echo $dog->speak(); // 输出: Buddy says Woof!
?>

接口与抽象类

php
复制编辑
<?php

// 抽象类
abstract class Shape {
    abstract public function area();
}

// 接口
interface Drawable {
    public function draw();
}

class Circle extends Shape implements Drawable {
    private $radius;

    public function __construct($radius) {
        $this->radius = $radius;
    }

    public function area() {
        return pi() * $this->radius * $this->radius;
    }

    public function draw() {
        echo "Drawing a circle with radius " . $this->radius . "\n";
    }
}

$circle = new Circle(5);
echo "Area: " . $circle->area() . "\n";  // 输出圆的面积
$circle->draw();  // 输出:Drawing a circle with radius 5
?>

2. 使用命名空间

php
复制编辑
<?php
// File: Library/Book.php
namespace Library;

class Book {
    public function __construct() {
        echo "This is a book from the Library namespace.";
    }
}

// File: Main.php
require_once 'Library/Book.php';

use Library\Book;

$book = new Book(); // 输出:This is a book from the Library namespace.
?>

3. PHP 设计模式 - 单例模式

php
复制编辑
<?php

class Singleton {
    private static $instance = null;

    // 构造方法私有,避免外部实例化
    private function __construct() {}

    // 获取单例实例
    public static function getInstance() {
        if (self::$instance === null) {
            self::$instance = new Singleton();
        }
        return self::$instance;
    }

    // 防止外部 clone
    private function __clone() {}

    // 防止外部反序列化
    private function __wakeup() {}
}

// 获取唯一实例
$instance1 = Singleton::getInstance();
$instance2 = Singleton::getInstance();

echo $instance1 === $instance2 ? "同一个实例" : "不同的实例";  // 输出:同一个实例
?>

4. PHP 异常与错误处理

php
复制编辑
<?php

// 自定义异常类
class CustomException extends Exception {
    public function errorMessage() {
        return "错误: " . $this->getMessage();
    }
}

function testException($value) {
    if ($value < 1) {
        throw new CustomException("值小于1");
    }
    return "值是: " . $value;
}

try {
    echo testException(0);  // 会抛出异常
} catch (CustomException $e) {
    echo $e->errorMessage();  // 输出:错误: 值小于1
}
?>

5. 性能优化:缓存机制

使用 APCu 缓存

php
复制编辑
<?php

// 设置缓存
apcu_store('user_data', ['name' => 'Alice', 'age' => 25]);

// 获取缓存
$data = apcu_fetch('user_data');
if ($data) {
    echo "缓存数据: " . json_encode($data);
} else {
    echo "没有缓存数据";
}
?>

文件缓存

php
复制编辑
<?php
function setCache($key, $data) {
    $cacheFile = 'cache/' . md5($key) . '.cache';
    file_put_contents($cacheFile, serialize($data));
}

function getCache($key) {
    $cacheFile = 'cache/' . md5($key) . '.cache';
    if (file_exists($cacheFile)) {
        return unserialize(file_get_contents($cacheFile));
    }
    return false;
}

setCache('user_info', ['name' => 'Alice', 'age' => 30]);
$data = getCache('user_info');
echo json_encode($data);  // 输出:{"name":"Alice","age":30}
?>

6. PHP异步编程 - 使用 pthreads 扩展 (PHP7之前)

由于PHP内建并不支持异步编程(直到PHP8引入了Fiber),但你可以使用扩展如 pthreads(PHP7之前)或 Swoole 来实现并发。

php
复制编辑
// PHP7之前的异步例子
class MyThread extends Thread {
    public function run() {
        echo "异步执行中...\n";
    }
}

$thread = new MyThread();
$thread->start();
?>

海尔源码haierym.com