. PHP Design Patterns . PHP Design Patterns PHP OO Static Basics

PHP Design Patterns PHP OO Static Basics

PHP Static Basics


Here are examples of creating and using static variables and function in a class.

The static variable $red is called by the function getStaticVarRed() and the static function staticGetStaticVarRed(), as well as directly by testOOPHPStatic.

Note that within it's own class a static variable or funtion should be referenced by self::variable or self::function(), instead of using this->. In an other class a static should be referenced byt the full name of the class with a double colon and the name of the variable or function, such as classname::$varname or classname::functioname().




OOPHPStatic.php

//copyright Lawrence Truett and FluffyCat.com 2007, all rights reserved

  //OOPHPStatic - a simple OO PHP Class with 
  //                         a static variable and function
  
  class OOPHPStatic {
    
    //a static variable, 
    static $red = 'RED';  
    
    public function getStaticVarRed() {
      return self::$red;
    }  

    public static function staticGetStaticVarRed() {
      return self::$red;
    }    
  
  }
download source, use right-click and "Save Target As..." to save with a .php extension.


testOOPHPStatic.php


//copyright Lawrence Truett and FluffyCat.com 2007, all rights reserved

  include_once('OOPHPStatic.php');

  define('BR', '<'.'BR'.'>');

  echo 'TESTING OOPHPStatic'.BR;
  echo BR;
  
  echo 'test 1 - show the static var directly'.BR;
  echo 'red: '.OOPHPStatic::$red;
  echo BR.BR;

  echo 'test 2 - show the static var using a class instance'.BR;
  $classOne = new OOPHPStatic();
  echo 'red: '.$classOne->getStaticVarRed();
  echo BR.BR;

  echo 'test 3 - show the static var using a static function'.BR;
  echo 'red: '.OOPHPStatic::staticGetStaticVarRed();
  echo BR.BR;

  echo 'END TESTING OOPHPStatic'.BR;

download source, use right-click and "Save Target As..." to save with a .php extension.


output of testOOPHPStatic.php

TESTING OOPHPStatic

test 1 - show the static var directly red: RED

test 2 - show the static var using a class instance red: RED

test 3 - show the static var using a static function red: RED

END TESTING OOPHPStatic


References

Design Patterns

Design Patterns by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides

PHP 5

The Official PHP web site
Core PHP Programming, 3rd Edition by Leon Atkinson and Zeev Suraski
Sign In
to add the first comment for PHP Design Patterns PHP OO Static Basics.