Home  >  Article  >  Backend Development  >  Let’s talk about singleton mode and static variables in PHP

Let’s talk about singleton mode and static variables in PHP

青灯夜游
青灯夜游forward
2020-07-24 17:06:352699browse

Let’s talk about singleton mode and static variables in PHP

In PHP, there are no static variables in the general sense. Unlike Java and C, the survival period of static variables in PHP is only the session period of each PHP, so it is destined that there will be no static variables like Java or C.

Static variables in PHP

In PHP, the meaning of static variables is only in a certain structure (method or class ), its scope is within this file.

function test(){
    static $var = 1; 
    echo $var++.'';
}
test();
test();
test();
//OutPut
//1
//2
//3

In the three calls of function test, the variable $var exists in the three calls, and will be incremented by 1 each time, without being cleared or reset
So we can draw a conclusion , static variables always exist in the life cycle of the current structure. In the current example, the life cycle of the test function is the current PHP script, which is valid as long as the program is not released.

Static variables are in the class

And in the class, the code probably looks like this

class A
{
    private static $a = 1; 
    private $b = 2;
    public function add()
    {
        echo self::$a++.'';
        echo $this->b++.'';
    }
}
$class1 = new A();
$class1->add();
$class1->add();
$class2 = new A();
$class2->add();
$class2->add();
//Output
//1
//2
//2
//3
//3
//2
//4
//3

From the above Judging from the running results of the class, we also got the same results in the function

So to summarize,

PHP’s static variables are in the life cycle of the corresponding structure Permanent existence, and the value remains consistent, no matter how many times the structure is called or instantiated.

In fact, this is the difference between dynamic variables and static variables. See this article for details. Dynamic variables are only valid within the class, while static variables are within the current PHP script.

Static variables are in singleton mode

Look at the singleton mode again

class A
{
    private static $instance = null;
    private $b = 1;
    public static function get_instance()
    {
        if(self::$instance == null){
            $classname = __CLASS__;
            self::$instance = new $classname(); 
        }
        return self::$instance;
    }
    public function add()
    {
        $this->b++;
    }
    public function show()
    {
        echo $this->b;
    }
}
$a = A::get_instance();
$b = A::get_instance();
//此处$a和$b变量完全相同!
$a->add();
$a->show();
echo '';
$b->show();
//output
//2
//2

At this time, due to the singleton The example mode exists, making $a and $b exactly the same object, so if you need to share data between them, there is no need for static variables (nonsense, just yourself. Because at any time, there will only be this class in the application. An instance exists! No matter how many times you call the singleton, the data inside will not be re-instantiated.)

So, in the singleton mode, static variables have no meaning at all. Of course, if you have nothing to do and insist on using the new method to initialize the object, that's fine. At this time, the singleton mode is broken and returns to the state without singleton mode.

If you want to prevent using new to instantiate objects, you can consider setting the __construct function of the class as a private attribute

class A
{
    private static $instance = null;
    private $b = 1;
    private function __construct()
    {
    //Code in this function
    //could not be get out of the class
    }
    public static function get_instance()
    {
        if(self::$instance == null){
            $classname = __CLASS__;
            self::$instance = new $classname();
        }
        return self::$instance;
    }
    public function add()
    {
        $this->b++;
    }
    public function show()
    {
        echo $this->b;
    }
}
$a = A::get_instance();
$b = A::get_instance();
//此处$a和$b 变量完全相同!
$a->add();
$a->show();
echo '
';
$b->show();
//output
//2
//2
  
//如果尝试用new来实例化的话
$c = new A();
//output
//Fatal error: Call to private A::__construct() from invalid context in
//如果需要A类的实例化对象,只能通过开放的get_instance静态方法进行初始化

Advantages: The singleton mode can avoid a large number of new operations, because each A new operation will consume memory resources and system resources

Disadvantages: In PHP, all variables, whether they are global variables or static members of the class, are page-level. Each time the page is executed, it will be refreshed. New objects created will be cleared after the page is executed. It seems that the PHP singleton mode is meaningless, so I think the PHP singleton mode is only for multiple application scenarios when a single page-level request occurs and needs to share the same Object resources are very meaningful

Related tutorial recommendations: "PHP Tutorial"

The above is the detailed content of Let’s talk about singleton mode and static variables in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete