PHP 面向对象基础
面向对象编程(OOP)是 PHP 现代开发的核心范式,通过类和对象组织代码。
类与对象
class User { // 属性 public string $name; public int $age; private string $password;`// 构造函数 public function __construct(string $name, int $age, string $password) { $this->name = $name; $this->age = $age; $this->password = password_hash($password, PASSWORD_DEFAULT); }
// 方法 public function greet(): string { return "你好,我是 {$this->name},今年 {$this->age} 岁。"; }
public function verifyPassword(string $input): bool { return password_verify($input, $this->password); } }
// 创建对象 $user = new User("张三", 25, "secret123"); echo $user->greet(); // 你好,我是 张三,今年 25 岁。 echo $user->verifyPassword("secret123"); // true ?> ``
访问修饰符
修饰符 类内 子类 外部 public ✅ ✅ ✅ protected ✅ ✅ ❌ private ✅ ❌ ❌ Getter / Setter
php <?php class Product { private float $price;`public function getPrice(): float { return $this->price; }
public function setPrice(float $price): void { if ($price < 0) throw new InvalidArgumentException("价格不能为负"); $this->price = $price; } }
$p = new Product(); $p->setPrice(99.9); echo $p->getPrice(); // 99.9 ?>
`继承
php <?php class Animal { public function __construct(protected string $name) {}`public function speak(): string { return "{$this->name} 发出声音"; } }
class Dog extends Animal { public function speak(): string { return "{$this->name} 说:汪汪!"; }
public function fetch(): string { return "{$this->name} 去捡球了"; } }
class Cat extends Animal { public function speak(): string { return "{$this->name} 说:喵喵!"; } }
$dog = new Dog("旺财"); $cat = new Cat("咪咪");
echo $dog->speak(); // 旺财 说:汪汪! echo $cat->speak(); // 咪咪 说:喵喵! echo $dog->fetch(); // 旺财 去捡球了 ?>
`抽象类与接口
php <?php // 抽象类:不能直接实例化 abstract class Shape { abstract public function area(): float;`public function describe(): string { return "这个形状面积是 " . $this->area(); } }
// 接口:定义契约 interface Drawable { public function draw(): string; }
class Circle extends Shape implements Drawable { public function __construct(private float $radius) {}
public function area(): float { return M_PI $this->radius * 2; }
public function draw(): string { return "画一个半径为 {$this->radius} 的圆"; } }
$c = new Circle(5); echo $c->area(); // 78.539... echo $c->describe(); // 这个形状面积是 78.539... echo $c->draw(); // 画一个半径为 5 的圆 ?>
`静态属性与方法
php <?php class Counter { private static int $count = 0;`public static function increment(): void { self::$count++; }
public static function getCount(): int { return self::$count; } }
Counter::increment(); Counter::increment(); Counter::increment(); echo Counter::getCount(); // 3 ?>
`Trait(代码复用)
php <?php trait Timestampable { private ?DateTime $createdAt = null; private ?DateTime $updatedAt = null;`public function touch(): void { $now = new DateTime(); if (!$this->createdAt) $this->createdAt = $now; $this->updatedAt = $now; }
public function getCreatedAt(): ?DateTime { return $this->createdAt; } }
class Article { use Timestampable;
public function __construct(public string $title) { $this->touch(); } }
$article = new Article("PHP 教程"); echo $article->getCreatedAt()->format('Y-m-d'); // 今天日期 ?>
``php <?php class MagicClass { private array $data = [];魔术方法
// 访问不存在的属性 public function __get(string $name): mixed { return $this->data[$name] ?? null; }
// 设置不存在的属性 public function __set(string $name, mixed $value): void { $this->data[$name] = $value; }
// 对象转字符串 public function __toString(): string { return json_encode($this->data, JSON_UNESCAPED_UNICODE); } }
$obj = new MagicClass(); $obj->name = "张三"; $obj->age = 25; echo $obj->name; // 张三 echo $obj; // {"name":"张三","age":25}