static static variables, static methods

Below, the static variable is the prefix of the static keyword, non-static variable that is a normal variable.

An ordinary static variables:

1. Local variables will be automatically released upon completion of a function, but with static local variable declaration will not be released, its life cycle is global visibility within the block.

2. Use static variables declared saves the last value is called, that is, will only be initialized once , therefore static local variable can be used as a global variable .

 

 The output of this example was 0,1,2

<?php 
	function myTest()
	{
    	static $x=0;
   		echo $x;
   	 	$x++;
	} 
	myTest();
	myTest();
	myTest();
?>

 

Second, the static member variables:

1. static data member variables:

Code as follows: defining a person class, age variable static data member variable.

Two ways to access static variables: 1. Variable Name 2. Class name :: :: object name object name 

Static member variables are part of the class, does not belong to any object, so you can share information between objects , different instances of the object is accessed with a static variable, static variable in a modified object, another static object access variable values also change.

The best access to static data using static function . When accessing the static data using non-static member variables function, should be non-inline function calls, i.e. body declared in the class, the class defined function in vitro.

2. static function member variables:

The basic nature of the data variable members is basically the same, it is worth noting that it is best not access non-static data in static functions, because the need to access non-static data with objects and static functions can access the class name. To use non-static functions to access non-static data .

 

The following example is a PHP example, access to other languages ​​$ removed.

<?php  
	class Person{  
		static $age = 10;
		 
		static function des(){ 
			//self:指的是当前的类   $this指的是当前的实例对象 
			echo "<hr>".self::$age;
		}
		//构造方法
		function __construct(){//只要创建对象,构造方法就会自动执行
			echo "对象创建";
		}
		function __destruct(){//默认程序执行完成后调用析构方法
			echo "死亡方法";		
		}
	} 
	
//1.实例化两个对象per1,per2
	$per1 = new Person();
	$per2 = new Person();
	
//2.访问静态变量的两种方式: 
	//1.通过类访问静态变量 ---------
	echo Person::$age;
	//2.直接通过实例对象访问常量--------
	echo $per1::$age;
	  
//3.不同实例对象所访问的静态变量是同一个(共享)
	echo $per1::$age;//输出10
	echo $per2::$age;//输出10
	
	//所以在一个对象中修改静态变量,别的对象访问的静态变量值也发生改变
	$per2::$age=100;
	echo $per1::$age;//输出100
	 
//4.释放内存
	$per2 = null; 
	    
//5.调用静态方法:静态方法不会每个实例都去初始化,类似于原型方法
	Person::des();
 
?>

 

 

 


 

Published 22 original articles · won praise 3 · views 10000 +

Guess you like

Origin blog.csdn.net/floracuu/article/details/78106274