PHP设计模式之单例模式

xiaoxiao2021-02-28  81

<?php include "function.php"; class Db{ private $username="mytest"; private $password="1126254578"; private $servername="127.0.0.1"; private $dbname="mytest"; static private $conn=null; function __construct(){ echo "construct"; $dns="mysql:host=".$this->servername.";dbname=".$this->dbname; self::$conn=new PDO($dns,$this->username,$this->password); self::$conn->exec("set names utf8"); } static function connect(){ if (self::$conn==null) { new Db; } return self::$conn; } }

/************************************************************ 单例模式:保证系统中只有一个实例 1.this是指向对象实例的一个指针 2.self是类本身的引用self:: pdo,Db:: pdo 3.parent是对父类的引用 4.直接通过Db::connect()调用静态函数 5.静态成员变量只有new Db的时候初始化值 6.静态函数只能访问静态成员变量,不能访问普通成员变量 7.通过定义私有构造函数,拷贝函数,阻止外部实例化类,因为私有属性只能在函数内部调用 **************************************************************/ github:https://github.com/comeonjy/php

转载请注明原文地址: https://www.6miu.com/read-71495.html

最新回复(0)