background image

Php

基础 PHP 多例模式

学习 java 就知道设计模式中有多例模式
学习 java 就知道设计模式中有多例模式:
1、多例类可以有多个实例
2、多例类必须能够自我创建并管理自己的实例,并向外界提供自己的实例。
大家都知道 PHP 单例模式,却很少说 PHP 多例模式,下面是在 wikipedia 上看到的 PHP
多例模式的例子:
代码如下:
<?php 

abstract

 

class

 Multiton { 

private

 

static

 

$instances

 = 

array

(); 

public

 

static

 

function

 getInstance() { 

$key

 = get_called_class() . serialize(func_get_args()); 

if

 (!isset(self::

$instances

[

$key

])) { 

$rc

 = 

new

 ReflectionClass(get_called_class()); 

self::

$instances

[

$key

] = 

$rc

->newInstanceArgs(func_get_args()); 

return

 self::

$instances

[

$key

]; 



 

class

 Hello 

extends

 Multiton { 

public

 

function

 __construct(

$string

 = 'World') { 

echo

 "Hello $string\n"; 



 

class

 GoodBye 

extends

 Multiton { 

public

 

function

 __construct(

$string

 = 'my', 

$string2

 = 'darling') { 

echo

 "Goodbye $string $string2\n"; 



 

$a

 = Hello::getInstance('World'); 

$b

 = Hello::getInstance('bob'); 

// $a !== $b