Home  >  Article  >  Backend Development  >  Introduction to PHP multiple instance mode_PHP tutorial

Introduction to PHP multiple instance mode_PHP tutorial

WBOY
WBOYOriginal
2016-07-21 15:03:091127browse

If you learn Java, you will know that there are multiple instances of design patterns:

1. A multi-instance class can have multiple instances
2. A multi-instance class must be able to create and manage its own instances, and provide its own instances to the outside world.

Everyone knows the PHP singleton mode, but few talk about the PHP multi-case mode. The following is an example of the PHP multi-case mode seen on Wikipedia:

Copy code The code is as follows:

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 $ stringn";
}
}

class GoodBye extends Multiton {
public function __construct($string = 'my', $string2 = 'darling') {
echo "Goodbye $string $string2n";
}
}

$a = Hello::getInstance('World');
$b = Hello::getInstance('bob');
// $a !== $b

$c = Hello::getInstance('World');
// $a === $c

$d = GoodBye::getInstance();
$e = GoodBye::getInstance();
// $d === $e

$f = GoodBye::getInstance('your' );
// $d !== $f
?>

You can see that the PHP multi-instance mode requires getInstance() to pass the key value. For a given key value, the PHP multi-instance mode will only have a unique object instance. The PHP multi-instance mode saves memory and ensures multiple instances of the same object. instances do not conflict.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/327868.htmlTechArticleIf you learn java, you will know that there are multiple instances in the design pattern: 1. A multi-instance class can have multiple instances 2. Multi-instance classes must be able to create and manage their own instances, and provide their own implementations to the outside world...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn