Php static variables and static methods

Source: Internet
Author: User
Many of my friends may be confused about the usage and differences between static variables and static methods in php. I will introduce some understanding of static variables and static methods based on my own experience. In PHP, quiet

Many of my friends may be confused about the usage and differences between static variables and static methods in php. I will introduce some understanding of static variables and static methods based on my own experience.

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.

Use static variables

Another important feature of the 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:

Demonstrate examples of static variables,The code is as follows:

  1. Function Test ()
  2. {
  3. $ A = 0;
  4. Echo $;
  5. $ A ++;
  6. }
  7. ?>

This function is useless, because every call sets the value of $ a to 0 and outputs "0". adding $ a ++ to the variable does not work, because once you exit this function, the variable $ a does not exist. to write a counting function that does not lose the value of this count, you need to define the variable $ a as static:

Example of using static variables,The code is as follows:

  1. Function Test ()
  2. {
  3. Static $ a = 0;
  4. Echo $;
  5. $ A ++;
  6. }
  7. ?>

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

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:

Static variables and recursive functions,The code is as follows:

  1. Function Test ()
  2. {
  3. Static $ count = 0;
  4. $ Count ++;
  5. Echo $ count;
  6. If ($ count <10 ){
  7. Test ();
  8. }
  9. $ Count --;
  10. }
  11. ?>

Note:Static variables can be declared according to the preceding example. if you assign a value to the expression in the declaration, parsing errors will occur.

Declare static variables,The code is as follows:

  1. Function foo (){
  2. Static $ int = 0; // correct
  3. Static $ int = 1 + 2; // wrong (as it is an expression)
  4. Static $ int = sqrt (121); // wrong (as it is an expression too)
  5. $ Int ++;
  6. Echo $ int;
  7. }
  8. ?>

Static method,The code is as follows:

  1. Class Fruit {
  2. Public static $ category = "I'm fruit ";
  3. Static function find ($ class)
  4. {
  5. $ Vars = get_class_vars ($ class );
  6. Echo $ vars ['Category '];
  7. }
  8. }
  9. Class Apple extends Fruit {
  10. Public static $ category = "I'm Apple ";
  11. }
  12. Apple: find ("Apple ");
  13. ?>
  14. // Program running result: 1 I'm Apple

Program List: override the base class method,The code for rewriting the base class in a derived class is as follows:

  1. Class Fruit
  2. {
  3. Static function Foo ($ class = _ CLASS __)
  4. {
  5. Call_user_func (array ($ class, 'color '));
  6. }
  7. }
  8. Class Apple extends Fruit
  9. {
  10. Static function Foo ($ class = _ CLASS __)
  11. {
  12. Parent: Foo ($ class );
  13. }
  14. Static function Color ()
  15. {
  16. Echo "Apple's color is red ";
  17. }
  18. }
  19. Apple: Foo (); // This time it works.
  20. ?>
  21. // Program running result: Apple's color is red

Program List: use of static arrays

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:

  1. Class Fruit
  2. {
  3. Static $ color = array ('color1' => 'red', 'color2' => 'yellow ');
  4. }
  5. Class Apple
  6. {
  7. Public function _ construct ()
  8. {
  9. Var_dump (Fruit: $ color );
  10. }
  11. }
  12. Class Banana
  13. {
  14. Public function _ construct ()
  15. {
  16. Fruit: $ color = FALSE;
  17. }
  18. }
  19. New Apple (); // prints array (2) {["color1"] => string (3) "red" ["color2"] => string (6) "yellow "}
  20. Echo' ';
  21. New Banana ();
  22. New Apple (); // prints bool (false)
  23. ?>

Program List: in the Singleton mode again, Static is really cool. The following Program demonstrates how to obtain an existing instance. the code is as follows:

  1. Class Singleton {
  2. Private static $ instance = null;
  3. Private $ value = null;
  4. Private function _ construct ($ value ){
  5. $ This-> value = $ value;
  6. }
  7. Public static function getInstance (){
  8. If (self: $ instance = null ){
  9. Echo"
    New
    ";
  10. Self: $ instance = new Singleton ("values ");
  11. }
  12. Else {
  13. Echo"
    Old
    ";
  14. }
  15. Return self: $ instance;
  16. }
  17. }
  18. $ X = Singleton: getInstance ();
  19. Var_dump ($ x); // returns the new object
  20. $ Y = Singleton: getInstance ();
  21. Var_dump ($ y); // returns the existing object
  22. ?>

For example, static variables and static methodsThe code is as follows:

  1. Class {
  2. Static $ I = 10;
  3. Public function set ($ n)
  4. {
  5. Self: $ I = $ n;
  6. }
  7. Public function get ()
  8. {
  9. Return self: $ I;
  10. }
  11. }
  12. $ A = new ();
  13. $ A-> set (11 );
  14. $ A1 = new ();
  15. 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. it is explained in java, in fact, static variables of a class use 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, therefore, static variables are initialized after the file is loaded, while static methods are registered. This can be understood, why is the java class entry like this? the code is as follows:

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 I do not always use static calls. I mainly 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 lot of memory (not verified) when it is not instantiated, so it is not recommended to set a method to static for infrequent access or special needs;

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.