PHP Implementation Singleton () Singleton pattern example, singleton instance
In this paper, the method of implementing Singleton () Singleton mode in PHP is described. Share to everyone for your reference. The implementation method is as follows:
The common.php file is as follows:
Copy the Code code as follows: <?php
Class CC
{
private static $ins;
public static function Singleton ()
{
if (!isset (self:: $ins)) {
$c = __class__;
Self:: $ins = new $c;
}
Return self:: $ins;
}
Public Function Eventresult ($Id)
{
return $Id;
}
}
?>
The index.php file is as follows:
Copy the Code code as follows:
Test
<?php
Require ' common.php ';
$objCC =cc::singleton ();
$r = $objCC->eventresult (7);
Print_r ($objCC);
echo $r. "
";
?>
I hope this article is helpful to everyone's PHP programming.
For the singleton pattern in Java
Package test;
public class Singleton {
Private Singleton S;
Private Singleton ()
{
}
public static Singleton Getsigleton ()
{
if (s==null) s=new Singleton ();
return s;
}
}
This is a singleton mode, I think it should not be annotated, the principle is that the construction method of the class private, all outside can not be called, can not be new Singleton ();
To get an instance, you have to invoke its static method Getsigleton () , which is Singleton.getsigleton (), will return an instance of Singleton, note the statement in this method, that is, if you are calling this method for the first time, then it will give you a new instance, and the subsequent call to get is this instance, that is, from the beginning to the end there is only one singleton Example, this is the singleton pattern.
Java Singleton mode (singleton) problem
In the code you give, the singleton is not synchronous
DAO is also generally used in a singleton mode
In the DAO class, the member variables of the class will appear as you say concurrency security, but general DAO's class variables are related to the data source connection, generally the same, so even concurrent calls do not affect.
Local variables in the DAO method are thread independent and there are no concurrency conflicts.
http://www.bkjia.com/PHPjc/907283.html www.bkjia.com true http://www.bkjia.com/PHPjc/907283.html techarticle PHP Implementation Singleton () Singleton mode instance, singleton example this paper describes the implementation of PHP Singleton () Singleton mode method. Share to everyone for your reference. The concrete implementation method is as follows: ...