Php static variables and static methods

Source: Internet
Author: User
Tags vars

In PHP, static variables are interpreted as variables that exist in the class scope. They are assigned a value during the first initialization and will not be re-assigned during class initialization, it is mainly used for variable sharing when a class has multiple instances. The following is the PHP static variable usage code:

Use static variables

Another important feature of variable range is static variable ). Static variables only exist in local function domains, but their values are not lost when the program runs out of this scope. Take a look at the following example:

Example 7-4. Example of static variables

The code is as follows: Copy code
<? Php
Function Test ()
{
$ A = 0;
Echo $;
$ A ++;
}
?>

 

This function is useless, because every call will set the value of $ a to 0 and output "0 ". Adding $ a ++ to the variable does not work, because $ a does not exist once you exit this function. To write a counting function that does not lose the current count value, you must define variable $ a as static:
Example 7-5. Example of using static variables

The code is as follows: Copy code

<? Php
Function Test ()
{
Static $ a = 0;
Echo $;
$ A ++;
}
?>
 

Now, every time you call the Test () function, the value of $ a is output and added with one.

Static variables also provide a method for processing recursive functions. A recursive function is a function that calls itself. Be careful when writing recursive functions, because infinite recursion may occur. Make sure there are sufficient methods to abort recursion. The simple function calculates 10 recursively and uses the static variable $ count to determine when to stop:

Example 7-6. Static variables and recursive functions

The code is as follows: Copy code

<? Php
Function Test ()
{
Static $ count = 0;

$ Count ++;
Echo $ count;
If ($ count <10 ){
Test ();
}
$ Count --;
}
?>

 
 

Note: static variables can be declared according to the preceding example. If a value is assigned to the expression result in the declaration, the parsing error occurs.

Example 7-7. Declare static variables

The code is as follows: Copy code

<? Php
Function foo (){
Static $ int = 0; // correct
Static $ int = 1 + 2; // wrong (as it is an expression)
Static $ int = sqrt (121); // wrong (as it is an expression too)

$ Int ++;
Echo $ int;
}
?>


Static method

The code is as follows: Copy code

 
<? Php
Class Fruit {
Public static $ category = "I'm fruit ";
   
Static function find ($ class)
 {
$ Vars = get_class_vars ($ class );
Echo $ vars ['Category '];
    }
}

Class Apple extends Fruit {
Public static $ category = "I'm Apple ";
}

Apple: find ("Apple ");
?>

Program running result:

1 I'm Apple

Program List: override the base class method

Override the method of the base class in the derived class.

The code is as follows: Copy code

 
<? Php
Class Fruit
{
Static function Foo ($ class = _ CLASS __)
    {
Call_user_func (array ($ class, 'color '));
    }
}

Class Apple extends Fruit
{
Static function Foo ($ class = _ CLASS __)
    {
Parent: Foo ($ class );
    }

Static function Color ()
    {
Echo "Apple's color is red ";
    }
}

Apple: Foo (); // This time it works.
?>


Program running result:

Apple's color is red

Program List: use of static arrays
Both static and const scopes can be accessed using the: operator. If you want to use the: Operator to access the array, you need to declare the array as static in advance.


 

The code is as follows: Copy code

<? Php
Class Fruit
{
Static $ color = array ('color1' => 'red', 'color2' => 'yellow ');
}

Class Apple
{
Public function _ construct ()
   {
Var_dump (Fruit: $ color );
   }
}

Class Banana
{
Public function _ construct ()
  {
Fruit: $ color = FALSE;
  }
}

New Apple (); // prints array (2) {["color1"] => string (3) "red" ["color2"] => string (6) "yellow "}
Echo '<br/> ';
New Banana ();
New Apple (); // prints bool (false)
?>

Program List: Another singleton mode
Static is really cool. The following program demonstrates how to obtain an existing instance.

The code is as follows: Copy code

   
<? Php
Class Singleton {

Private static $ instance = null;
Private $ value = null;

Private function _ construct ($ value ){
$ This-> value = $ value;
    }

Public static function getInstance (){
If (self: $ instance = null ){
Echo "<br> new <br> ";
Self: $ instance = new Singleton ("values ");
        } 
Else {
Echo "<br> old <br> ";
        }
Return self: $ instance;
    }

}

$ X = Singleton: getInstance ();
Var_dump ($ x); // returns the new object
$ Y = Singleton: getInstance ();
Var_dump ($ y); // returns the existing object
?>

Example

Static variables and static methods

The code is as follows: Copy code

Class {
Static $ I = 10;
Public function set ($ n)
 {
Self: $ I = $ n;
 }
Public function get ()
 {
Return self: $ I;
 }
}
$ A = new ();
$ A-> set (11 );
$ A1 = new ();
Echo $ a1-> get ();

The output is 11. We can see that after Class A is instantiated for the second time, the static variable $ I is still consistent with the value of $ I set after the last instantiation. In java, a static variable of a class uses a memory space in multiple instances. I think this explanation is easier to understand. Because static variables and static methods can be used without instantiation, static variables will be initialized after the file is loaded, and static methods will be registered. This explains why the java class entry is like this:

The code is as follows: Copy code

Public static void main (String [] args)
{
}

I used to think that static methods can be directly used without instantiation, saving the huge overhead of instantiation. Therefore, when using a class method, I prefer direct static calls to avoid instantiation. I have argued with my colleagues many times about this issue. He does not advocate static calling and has the following ideas:

1. Instantiation classes are more in line with the idea of object-oriented programming;
2. Static call methods do not save much on consumption.
I still stick to my opinion on this issue, but it is not always static call. I have the following ideas:
1. static variables are initialized when the file is loaded. Therefore, if there are multiple classes and multiple static variables and methods in the class, it is bound to consume a large amount of memory (not verified) when it is not instantiated ). Therefore, for infrequent access or special needs, we do not recommend that you set a method to static;
2. For classes with frequent calls, I strongly recommend that you use static and static methods to share both memory space and data. You will find that the base classes of mainstream PHP frameworks are static call methods.

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.