This article mainly introduces the static variable of PHP introduction, has a certain reference value, now share to everyone, the need for friends can refer to
1 static variables within a function
Only works inside the function, and after each call, the value of the static variable is changed on the basis of the last call. When defined, if the initial value is given, then the statement executes only once
For example: No matter how many times the GetData () function is called static $c 2 = 0; This statement will only be executed once
function GetData () {static $c 2 = 0;//initialization statement $C2 = $c 2 + 1;echo "$c 2\n";} GetData ();//Results 1getdata ();//Result 2
2 Static class member variables
1. Static member variables of a class belong to this class only, but all instances of the class share this static member variable
2. Static member variables can be accessed without instantiation and are accessed faster
For example:
Class C1 {//use counter;static $c 2=1;public Function Inc () {static $c; $c = $c + 1;echo "$c \ n";}} $o = new C1 (); $o->inc (); echo 1$p = new C1 (); $p->inc (); Echo 2echo "; $p:: $c 2=5;echo C1:: $c 2;//echo 5 static member variables do not need to be instantiated to access, and access speed some echo"; Echo $p:: $c 2;//echo 5echo "; Echo $o:: $ C2;//echo 5
1.static class method
A static method of a class can only access static member variables and cannot access non-static member variables (error if any)
Class C3 {//use counter;public static $c 3=1;public $c 5 =5;public static function inc1 () {echo C3:: $c 3;//}public static Fun Ction Inc2 () {echo $this->c5;//error $this not allowed in static method}}c3::inc1 ();//Echo 1c3::inc2 (); Fatal error:uncaught error:using $this When not in object context
Static variables of 2.Trait
Static variables of the trait are not affected by different classes when they are used
For example:
Trait Counter {public Function Inc () {static $c = 0; $c = $c + 1;echo "$c \ n";}} Class C1 {use Counter;} Class C2 {use Counter;} $o = new C1 (); $o->inc (); Echo 1$o->inc (); echo 2$b = new C1 (); $b->inc (); Echo 3$b->inc (); echo 4$p = new C2 (); $p->inc (); Echo 1$p->inc (); Echo 2
The above is the whole content of this article, I hope that everyone's learning has helped, more relevant content please pay attention to topic.alibabacloud.com!