在设计模式中,PHP实例通常用于实现单例模式、工厂模式和原型模式等。
class Singleton { private static $instance; private function __construct() {} public static function getInstance() { if (self::$instance === null) { self::$instance = new Singleton(); } return self::$instance; } } $singleton = Singleton::getInstance(); interface Shape { public function draw(); } class Circle implements Shape { public function draw() { echo "Drawing Circle"; } } class Square implements Shape { public function draw() { echo "Drawing Square"; } } class ShapeFactory { public function createShape($type) { if ($type === 'circle') { return new Circle(); } elseif ($type === 'square') { return new Square(); } return null; } } $factory = new ShapeFactory(); $circle = $factory->createShape('circle'); $circle->draw(); class Prototype { private $name; public function __construct($name) { $this->name = $name; } public function clone() { return clone $this; } } $prototype = new Prototype('Object'); $clone = $prototype->clone();