Php static variables define, static, const

Source: Internet
Author: User
Tags flock

 

Static variables only exist in the function scope. That is to say, static variables only exist in the stack. Generally, variables in a function are released after the function ends, such as local variables, but static variables do not. That is to say, when you call this function again, the value of this variable will be retained.

Simplest definition method

The define () function defines a constant.

Constants are similar to variables, except that:

After setting, the constant value cannot be changed.
The constant name does not need to start with the dollar sign ($)
The scope does not affect constant access.
A constant value can only be a string or number.
Syntax

Define (name, value, case_insensitive)

Class foo {
Static $ my_static = 5;
Public $ my_prop = 'bla ';
}

Print foo: $ my_static; copyright dedecms
$ Obj = new foo;
Print $ obj-> my_prop;
?>

Const is a constant, that is, the constant value from the beginning to the end of the program operation.

Class say_const {
Const charset = "China ";
Publice function say_hello (){
Echo slef: charset;
}
}
$ Const1 = new say_const ()'
$ Const1-> say_hello ();
?>

The output is "China"

The following is a complete static variable.

Function write_file ($ file, $ msg, $ usecheck = 5 ){
Static $ check = 1; // used here ~
$ F = @ fopen ($ file, "a + B ");
If ($ f ){
If (flock ($ f, lock_ex )){
Fwrite ($ f, $ msg );
Flock ($ f, lock_un );
Fclose ($ f );
} Else {
Fclose ($ f );
$ Check ++;
If ($ check <= $ usecheck ){
Sleep (1); // pause the program and wait for other processes to release the resource.
Write_file ($ file, $ msg );
}
}
} Else {
$ Check ++;
If ($ check <= $ usecheck ){
Sleep (1); // pause the program and wait for other processes to release the resource.
Write_file ($ file, $ msg );
}
}
}


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.