Create Constructors and destructor in PHP

Description

The following code shows how to create Constructors and destructor.

Example


<?php//from   w ww.jav  a  2  s .  com
  class Counter
  {
    private static $count = 0;

    function __construct()
    {
      self::$count++;
    }

    function __destruct()
    {
      self::$count--;
    }

    function getCount()
    {
      return self::$count;
    }
  }

  //create one instance
  $c = new Counter();

  //print 1
  print($c->getCount() . "<br>\n");

  //create a second instance
  $c2 = new Counter();

  //print 2
  print($c->getCount() . "<br>\n");

  //destroy one instance
  $c2 = NULL;

  //print 1
  print($c->getCount() . "<br>\n");
?>

The code above generates the following result.





















Home »
  PHP Tutorial »
    Language Basic »




PHP Introduction
PHP Operators
PHP Statements
Variable
PHP Function Create
Exception
PHP Class Definition