Home > Backend Development > PHP Tutorial > PHP implements singleton mode supplemented by calling instructions

PHP implements singleton mode supplemented by calling instructions

不言
Release: 2023-03-23 09:02:01
Original
1736 people have browsed it

The content of this article is the implementation of singleton mode in PHP with the help of calling instructions. Now I share it with everyone. Friends in need can refer to the content of this article


<?php
class Sim{
    //测试对象的值
    private $age = &#39;&#39;;
    //本类的一个对象
    private static $instance = null;
    //构造函数私有化 防止外部 new
    private function __construct($age)
    {
        $this->age = $age;
    }
    //禁止外部克隆
    private function __clone()
    {

    }
    //开放对外接口。
    public static function getInstance($age){
        if(!self::$instance instanceof self)
        {
            self::$instance = new self($age);
        }
        return self::$instance;
    }
    //测试打印
    public function showValue(){
        echo $this->age.&#39;<br>&#39;;
    }

}

$sim = Sim::getInstance(3);
$sim->showValue();
//重新赋值 并没有影响原来的对象属性值 可见是同一个对象在共享数据,以此来说明 单例
$sim = Sim::getInstance(3332);
$sim->showValue();
Copy after login


Print test results


Related recommendations:

PHP implements addition and subtraction verification Code

php implements the method of querying mysql and caching to redis

The above is the detailed content of PHP implements singleton mode supplemented by calling instructions. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template