php Wzorzec Singleton

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php Wzorzec Singleton相关的知识,希望对你有一定的参考价值。

<?php 

include 'Config.php';
include 'DB.php';

/*
$conf1 = Config::getInstance();
echo $conf1->getLanguage();

$conf2 = Config::getInstance()->setLanguage('en');
echo $conf1->getLanguage();
*/

$users = Db::getInstance()->query("SELECT * FROM users");

if ($users->count()) {
	foreach ($users->results() as $user) {
		echo $user->username . "<br>";
	}
}

?>
<?php 

class Db {
	public static $instance;

	private $_mysqli,
			$_query,
			$_results = [],
			$_count = 0;

	public static function getInstance() {
		if (self::$instance === null) {
			self::$instance = new Db();
		}
		return self::$instance;
	}

	public function __construct() {
		$this->_mysqli = new mysqli('localhost', 'root', '', 'loginapp');

		if ($this->_mysqli->connect_error) {
			die($this->_mysqli->connect_error);
		}
	}

	public function query($sql) {
		if ($this->_query = $this->_mysqli->query($sql)) {
			while ($row = $this->_query->fetch_object()) {
				$this->_results[] = $row;
			}
			$this->_count = $this->_query->num_rows;
		}
		return $this;
	}

	public function results() {
		return $this->_results;
	}

	public function count() {
		return $this->_count;
	}
}

?>

以上是关于php Wzorzec Singleton的主要内容,如果未能解决你的问题,请参考以下文章

PHP PHP Singleton类

php Quick Singleton类将包含在WordPress插件(或主题functions.php文件)中,它将创建一个简单的Person帖子类型并显示

Singleton(单例模式)

Laravel容器返回多个Singleton实例

与PDO和Singleton类的数据库连接

PHP7.3:如何在不使它在子类中重新声明的情况下,以最窄的范围继承一个受保护的静态属性?