1、单例模式
单例模式三要素:
- 拥有一个构造函数,并且为private
- 拥有一个静态成员变量来保持类的实例
- 拥有一个访问这个实例的静态方法
<?php
//Instan.php 单例类class Instan{static public $instance = null;private function __construct(){var_dump('new class');}public static function getInstance(){if(!self::$instance){self::$instance = new self();}return self::$instance;}public function getInfo(){echo 'Information...' . "<br />";}}
<?php
//test.phpinclude './Instan.php';Instan::getInstance()->getInfo();
Instan::getInstance()->getInfo();
Instan::getInstance()->getInfo();//在同一个进程中,无论调用多少次实例类,都只会实例化一次,这就是单例模式
2、注册树模式
- 注册树模式通过将对象实例注册到一棵全局的对象树上
- 需要的时候,从对象树上采摘下来使用
<?php
//test.phpinclude './abc';//只是为了演示注册树模式,生产环境不要这样写class Register{protected static $object = null;/*** 将对象实例挂到注册树上* @param $key* @param $object*/public static function set($key, $object){self::$object[$key] = $object;}/*** 获取注册树获取对象* @param $key*/public static function get($key){if(!isset(self::$object[$key])){self::$object[$key] = new $key;}return self::$object[$key];}/*** 从注册树上摘下* @param $key*/public static function unsetObj($key){unset(self::$object[$key]);}/*** 测试注册树*/public function test(){$abc = new Abc();self::set("Abc",$abc);//注册$res = self::get("Abc")->getAbc();//获取var_dump($res);//也可以直接get,因为get方法会自动注册self::get("Abc")->getAbc();}}
<?php
//abc.phpclass Abc
{public function getAbc(){var_dump('ABC');}
}
3、依赖注入(控制反转)
//Index.php 控制器class Index
{$person = new Person();$car = new Car();//此处的Car类可以灵活的换成其他类echo $person->driveCar($car);
}
//Person类class Person
{/*** 依赖:Person类依赖于Car类* 注入:Car类注入到Person类* @param $obj* @return mixed*/public function driveCar($obj){return $obj->run();}}
//Car类class Car
{public function run(){return '跑得快,跑得快...';}
}
4、反射
https://www.php.net/manual/zh/book.reflection.php
<?php
class Apple {public function firstMethod() { }final protected function secondMethod() { }private static function thirdMethod() { }
}$class = new ReflectionClass('Apple');
$methods = $class->getMethods();
var_dump($methods);
?>
array(3) {[0]=>&object(ReflectionMethod)#2 (2) {["name"]=>string(11) "firstMethod"["class"]=>string(5) "Apple"}[1]=>&object(ReflectionMethod)#3 (2) {["name"]=>string(12) "secondMethod"["class"]=>string(5) "Apple"}[2]=>&object(ReflectionMethod)#4 (2) {["name"]=>string(11) "thirdMethod"["class"]=>string(5) "Apple"}
}