单例模式的作用就是在整个应用程序的生命周期中,单例类的实例都只存在一个,同时这个类还必须提供一个访问该类的全局访问点。
首先创建一个单例类,可以直接使用这个单例类获得唯一的实例对象,也可以继承该类,使用子类实例化对象。
下面的代码使用子类进行实例对象创建
Singleton.php文件
<?phpnamespace test;class Singleton{ ???protected static $instance; ???private function __construct() ???{ ???} ???/* ???????static 的用法是后期静态绑定:根据具体的上下文环境,确定使用哪个类 ???*/ ???public static function getInstance() ???{ ???????/* ???????????$instance 如果为NULL,新建实例对象 ???????*/ ???????if (NULL === static::$instance) { ???????????echo ‘before‘ . PHP_EOL; ???????????static::$instance = new static(); ???????????echo ‘after‘ . PHP_EOL; ???????} ???????/* ???????????不为NULL时,则直接返回已有的实例 ???????*/ ???????return static::$instance; ???}}
SingletonTest.php子类文件
<?phpnamespace test;require_once(‘Singleton.php‘);class SingletonTest extends Singleton{ ???private $name; ???public function __construct() ???{ ???????echo ‘Create SingletonTest instance‘ . PHP_EOL; ???} ???public function setName($name) ???{ ???????$this->name = $name; ???} ???public function getName() ???{ ???????echo $this->name . PHP_EOL; ???}}/* ???SingletonTest instance*/$test_one = SingletonTest::getInstance();$test_one->setName(‘XiaoMing‘);$test_one->getName();/* ???$test_two 和 $test_one 获取的是同一个实例对象*/$test_two = SingletonTest::getInstance();$test_two->getName();
命令行下运行结果:
PHP设计模式------单例模式
原文地址:https://www.cnblogs.com/BluePegasus/p/8157499.html