php单例模式示例分享
这篇文章主要分享了一则php单例模式的示例,设计模式这些的花点心思基本的是能够理解的,当然要想很好的运用到项目上也是需要一定的实践,不能只是知道了解,或者说的是很厉害很懂的,一到要实际操作就不行了,废话就不多说了
单例模式主要使用于数据库的连接, 确保数据库一个类只有一个实例, 并且向整个系统提供这个实例。从而避免new操作消耗资源, 同时避免数据库出现too many connection信息.
要点有三个: 1. 必须只有一个实例。 2. 必须自动创建这个实例。 3. 必须向整个系统提供这个实例。
代码如下:
class mysql{
privete static $instance ;//保存实例
//构造函数声明为private, 防止直接创建对象
privete function __construct(){
// 实例化
}
//单例方法, 判断是否已经实例化,只实例化一次
public static function getInstance (){
if(!isset( self::$instance )){
self ::$instance = new self();
}
return self:: $instance;
}
//防止克隆对象
private function __clone (){
trigger_error ("not allow to clone.");
}
function test(){
echo "test" ;
}
}
$conn = mysql::getInstance ();
$conn->test ();
?>

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

WebStorm Mac version
Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
