---
title: "控制 PHP 类的实例化次数!"
author: "javaeyeren"
date: "2009-02-02T01:47:00Z"
tags: []
slug: "php"
draft: false
lastmod: "2009-02-02T01:47:00Z"
id: 601345
url: "https://javaeyeren.iteye.com/blog/601345"
---

# 控制 [php](http://blog.csdn.net/phphot "welcome to phphot,phper's home") 类的实例化次数!为了保证服务器资源的有效利用,而且一个类比方说模板啊,数据库什么的,在一个页面内只需要实例化一次!也就是在内存中只运行一个实例!那么为了避免重复实例化,那么控制 [php](http://blog.csdn.net/phphot "welcome to phphot,phper's home") 类的实例化次数,是很有必要的!方法其实很简单:就是给类一个外部接口,私有化(private)构造函数,抛弃可以在类外部使用new实例化该类的方法!以下,就是我给出的一个例子,相信大家一看就明白了!( PHP5 以上版本! ) &lt;?php class test{ const name = 'test'; public static $havenew = false; public $name = '我被限制为只能实例化一次了!'; private function \_\_construct(){ } function \_\_destruct(){ self::$havenew = false; } public function inter(){ if(self::$havenew){ echo '类 '.self::name.' 已被实例化!'; return NULL; }else{ self::$havenew = true; return new self; } } } $class1 = test::inter(); var\_dump($class1); echo '&lt;br /&gt;'; $class2 = test::inter(); var\_dump($class2); ?&gt; 这里都是实例通过test里inter()这个方法实例化对象的!因为构造本身不可以直接访问,所以也不存在可以使用new 来实例化!