PHP/Class/static properties — различия между версиями

Материал из Web эксперт
Перейти к: навигация, поиск
м (1 версия)
 
(нет различий)

Текущая версия на 07:00, 26 мая 2010

static class members

 
<?php
    class visitors
    {
        private static $visitors = 0;
        function __construct(){
            self::$visitors++;
        }
        static function getVisitors(){
            return self::$visitors;
        }
    }
    $visits = new visitors();
    echo visitors::getVisitors()."<br />";
    $visits2 = new visitors();
    echo visitors::getVisitors()."<br />";
?>



static class properties

<?php
   class visitors
   {
      private static $visitors = 0;
      function __construct()
      {
         self::$visitors++;
      }
      static function getVisitors()
      {
         return self::$visitors;
      }
   }
   $visits = new visitors();
   echo visitors::getVisitors()."<br />";
   $visits2 = new visitors();
   echo visitors::getVisitors()."<br />";
?>



Use the static modifier to change a member or method

 
<?php
class myclass {
  const MYCONST = 123;
  static $value = 567;
}
echo "myclass::MYCONST = " . myclass::MYCONST . "\n";
echo "myclass::$value = " . myclass::$value . "\n";
?>



Using Static Methods and Properties to Limit Instances of a Class (PHP 5 Only)

 
<?php
class Shop {
  private static $instance;
  public $name="shop";
  private function ___construct() {
  }
  public static function getInstance() {
    if ( empty( self::$instance ) ) {
    self::$instance = new Shop();
    }
    return self::$instance;
  }
}
$first = Shop::getInstance();
$first-> name="A";
$second = Shop::getInstance();
print $second -> name;
?>



Using the -> and :: operators to call hypnotize

 
<?php
    class Cat {
    }
class MyCat extends Cat {
    function MyCat(  ) {
    }
    public static function hypnotize(  ) {
      echo ("The cat was hypnotized.");
      return;
    }
}
MyCat::hypnotize(  );
$h_cat = new MyCat(  );
$h_cat->hypnotize(  );