Basic usage of static variables in php

Source: Internet
Author: User
Static variables only exist in the function scope, and static variables only exist in the stack. The next time you call this function, the value of this variable is retained. the static variable only exists in the function scope, and the static variable only exists in the stack. Generally, variables in a function are released after the function ends, such as local variables, but static variables do not. The value of this variable is retained the next time you call this function.

Basic usage of static variables

1. define static variables in the class
[Access modifier] static $ variable name;
2. how to access static variables
If there are two methods to access a class: self: $ static variable name, class name: $ static variable name
For out-of-class access: there is a method class name: $ static variable name

Example

The code is as follows:


Class Child {

Public $ name;
// Define and initialize a static variable $ nums
Public static $ nums = 0;
Function _ construct ($ name ){

$ This-> name = $ name;
}

Public function join_game (){

// Self: $ nums use static variables
Self: $ nums + = 1;

Echo $ this-> name. "joining snowman game ";

}


}

// Create three children

$ Child1 = new Child ("Li Yun ");
$ Child1-> join_game ();
$ Child2 = new Child ("Zhang Fei ");
$ Child2-> join_game ();
$ Child3 = new Child ("Tang Seng ");
$ Child3-> join_game ();

// Check the number of people playing games
Echo"
There is this ". Child: $ nums;

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.