PHP实现一个限制实例化次数的类示例

yipeiwu_com7年前PHP代码库

本文实例讲述了PHP实现一个限制实例化次数的类。分享给大家供大家参考,具体如下:

实现思路

  1. 定义一个static变量$count,用于保存实例化对象的个数
  2. 定义一个static方法create,通过该方法判断$count的值,进而判断是否进一步实例化对象。
  3. 定义构造函数,$count+1
  4. 定义析构函数,$count-1

实现代码

<?php
class demo{
  public $name;
  public static $count=0;
  private function __construct($name){
    echo "create $name <br/>";
    $this->name = $name;
    self::$count++;
  }
  public function __destruct(){
    echo "destory ".$this->name."<br/>";
    self::$count--;
  }
  public static function create($name){
    if(self::$count>2){
      die("you can only create at most 2 objects.");
    }else{
      return new self($name);
    }
  }
}
$one = demo::create("one");
$two = demo::create("two");
$two = null;
$three = demo::create("three");

运行结果:

create one
create two
destory two
create three
destory three
destory one

更多关于PHP相关内容感兴趣的读者可查看本站专题:《php面向对象程序设计入门教程》、《PHP数组(Array)操作技巧大全》、《PHP基本语法入门教程》、《PHP运算与运算符用法总结》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》

希望本文所述对大家PHP程序设计有所帮助。

相关文章

PHP实现求两个字符串最长公共子串的方法示例

本文实例讲述了PHP实现求两个字符串最长公共子串的方法。分享给大家供大家参考,具体如下: 前面一篇PHP实现求解最长公共子串问题的方法是基于java改进而来,这里再来看另一种公共子串算法...

PHP执行速率优化技巧小结

1.在可以用file_get_contents替代file、fopen、feof、fgets等系列方法的情况下,尽量用file_get_contents,因为他的效率高得多!但是要注意f...

php实现html标签闭合检测与修复方法

本文实例讲述了php实现html标签闭合检测与修复方法。分享给大家供大家参考。具体如下: html标签闭合检测与修复,说的有点大 , 并没有考虑的很完整,没有使用正则表达式, 适用于ht...

php命名空间设计思想、用法与缺点分析

本文实例讲述了php命名空间设计思想、用法与缺点。分享给大家供大家参考,具体如下: 相比C#等语言,你可以在php函数里面随意定义变量并赋值,而不用担心覆盖了全局变量,或者类变量;你也可...

php事务回滚简单实现方法示例

本文实例讲述了php事务回滚简单实现方法。分享给大家供大家参考,具体如下: $servername="localhost"; $username="root"; $password=...