转载自longlong's blog
- <?php
- function test(){
- static $var = 1;
- echo $var++.'<br />';
- }
- test();
- test();
- test();
- //OutPut
- //1
- //2
- //3
- ?>
- <?php
- class A
- {
- private static $a = 1;
- private $b = 2;
- public function add()
- {
- echo self::$a++.'<br />';
- echo $this->b++.'<br />';
- }
- }
- $class1 = new A();
- $class1->add();
- $class1->add();
- $class2 = new A();
- $class2->add();
- $class2->add();
- //Output
- //1
- //2
- //2
- //3
- //3
- //2
- //4
- //3
- <?php
- class A
- {
- private static $instance = null;
- private $b = 1;
- public static function get_instance()
- {
- if(self::$instance == null){
- $classname = __CLASS__;
- self::$instance = new $classname();
- }
- return self::$instance;
- }
- public function add()
- {
- $this->b++;
- }
- public function show()
- {
- echo $this->b;
- }
- }
- $a = A::get_instance();
- $b = A::get_instance();
- //此处$a和$b 变量完全相同!
- $a->add();
- $a->show();
- echo '<br />';
- $b->show();
- //output
- //2
- //2
- <?php
- class A
- {
- private static $instance = null;
- private $b = 1;
- private function __construct()
- {
- //Code in this function
- //could not be get out of the class
- }
- public static function get_instance()
- {
- if(self::$instance == null){
- $classname = __CLASS__;
- self::$instance = new $classname();
- }
- return self::$instance;
- }
- public function add()
- {
- $this->b++;
- }
- public function show()
- {
- echo $this->b;
- }
- }
- $a = A::get_instance();
- $b = A::get_instance();
- //此处$a和$b 变量完全相同!
- $a->add();
- $a->show();
- echo '<br />';
- $b->show();
- //output
- //2
- //2