PHP/Class/static properties

Материал из Web эксперт
Версия от 10:00, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

static class members

   <source lang="html4strict">

<?php

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

?>

 </source>
   
  


static class properties

   <source lang="html4strict">

<?php

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

?>

      </source>
   
  


Use the static modifier to change a member or method

   <source lang="html4strict">

<?php class myclass {

 const MYCONST = 123;
 static $value = 567;

} echo "myclass::MYCONST = " . myclass::MYCONST . "\n"; echo "myclass::$value = " . myclass::$value . "\n"; ?>

 </source>
   
  


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

   <source lang="html4strict">

<?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; ?>

 </source>
   
  


Using the -> and :: operators to call hypnotize

   <source lang="html4strict">

<?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( );

 </source>