Basic usage of static variables in PHP _php tutorial

Source: Internet
Author: User
Static variables exist only within the scope of the function, and static variables live only on the stack. General function variables are released after the function ends, such as local variables, but static variables do not. The value of the variable is preserved the next time the function is called.

Basic usage of static variables

1. Defining static variables in a class
[Access modifier] static $ variable name;
2. How to access static variables
If there are two methods to access in a class self::$ static variable name, class Name:: $ static variable name
If you are accessing outside the class: There is a method class name:: $ static variable name

Example
Copy CodeThe code is as follows:
Class child{

Public $name;
This defines and initializes a static variable $nums
public static $nums = 0;
function __construct ($name) {

$this->name= $name;
}

Public Function Join_game () {

Self:: $nums using static variables
Self:: $nums +=1;

echo $this->name. " Added snowmen game ";

}


}

Create three children

$child 1=new Child ("Li Kui");
$child 1->join_game ();
$child 2=new Child ("Zhang Fei");
$child 2->join_game ();
$child 3=new Child ("Tang priest");
$child 3->join_game ();

See how many people are playing games
echo "
Have this. " Child:: $nums;

http://www.bkjia.com/PHPjc/743925.html www.bkjia.com true http://www.bkjia.com/PHPjc/743925.html techarticle static variables exist only within the scope of the function, and static variables live only on the stack. General function variables are released after the function ends, such as local variables, but static variables do not. ...

  • 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.