为了达到这种目的,必须保证整个项目有且只有一个实例存在并提供一个访问点供全局访问.这就需要通过调用此类的一个共用静态方法来访问这个实例,也就是说此类不能在类外面去实例化,只能在类内部实例,而且是只能通过共用的静态方法调用实例;
最近在看php高级程序设计、模式、框架与测试一书,颇有感悟,与大家分享:
在做项目时,通常我们希望某些类实例一次就够了,比如共用配置类,模板操作类,数据库连接等等,这些类因为在整个项目开发中是通用的,如果实例多次实例就会占用资源.
为了达到这种目的,必须保证整个项目有且只有一个实例存在并提供一个访问点供全局访问.这就需要通过调用此类的一个共用静态方法来访问这个实例,也就是说此类不能在类外面去实例化,只能在类内部实例,而且是只能通过共用的静态方法调用实例;
那么怎么保证此类不能在外面实例化呢?需要此单例类必须拥有一个构造函数__construct,且设置为private(因为已经有__construct,不考虑默认的构造方法:直接用类名的方法的情况),这样就保证了不会在外面直接实例化!同时还需要声明一个静态方法变量来保存此类的实例,一个共用的静态方法来访问此实例,(因为要共用,所以声明为静态的,存放内存中的共用代码区部分).还需要创建一个空的私有的__clone()方法,以防止被克隆.
一个很典型的单例类如下:
实例代码如下:
<?php class Simple { /** * 单例类实例 * * @static * @var object Simple */ public static $_instance; //其他成员变量 /** * 构造方法 * * @return void */ private function __construct() { //写构造方法 } /** * 单例模式调用方法 * * @static * @return object Template */ public static function getInstance() { if (!self::$_instance instanceof self) self::$_instance = new self(); return self::$_instance; } /** * 声明一个空的私有克隆方法 * */ private function __clone() { } //其他方法 } //调用方式 $Simple = Simple::getInstance(); ?>
上面用到了 instanceof关键字,为比较操作符,返回布尔能够判断某个对象实例是否为制定的类型,或者是否从某个类继承,或者是否实现了某个特定接口
教程网址:
欢迎收藏∩_∩但请保留本文链接。

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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Dreamweaver Mac version
Visual web development tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Dreamweaver CS6
Visual web development tools