Static and static variables in PHP using the detailed _php example

Source: Internet
Author: User
Tags class definition instance method modifier static class

Static variables exist only within the scope of a function, that is, static variables live only on the stack. Normal variables are released after the function ends, such as local variables, but static variables do not. That is, the value of the variable is preserved the next time the function is called.

The variable becomes a static variable as long as it is preceded by a keyword static.

<?php
  function Test ()
  {
    static $nm =;
    $NM = $nm *;
    Print $nm. " <br/> ";
  }
  First execution, $nm = 
  test ();
  First execution, $nm = 
  test ();
  First execution, $nm = 
  test ();
? >

Program Run Result:
1
2
2
4
3
8

After the function test () is executed, the value of the variable $nm is saved.

Static properties, such as static members and static methods, are often used in class.

Program List: Static members of classes

The static variable $nm belongs to the class Nowamagic and not to an instance of the class. This variable is valid for all instances.

:: Is the scope-qualified operator, where the self scope is used instead of the $this scope, $this scope represents only the current instance of the class, Self:: Represents the class itself.

<?php
  class Nowamagic
  {public
    static $nm =;
    function Nmmethod ()
    {
      self:: $nm = =;
      echo Self:: $nm. ' <br/> ';
    }
  $nmInstance = new Nowamagic ();
  $nmInstance-> Nmmethod ();
  $nmInstance = new Nowamagic ();
  $nmInstance-> Nmmethod ();
? >

Program Run Result:
1
3
2
5

Program List: Static properties

<?php
  class Nowamagic
  {public
    static $nm = ' www.nowamagic.net ';
    Public Function Nmmethod ()
    {return
      self:: $nm;
    }
  }
  Class Article extends Nowamagic
  {public
    function Articlemethod ()
    {return
      parent:: $nm;
    }
  }
  //Through the action on the qualified operator access static variable
  print Nowamagic:: $nm. "<br/>";
  The method that invokes the class
  $nowamagic = new Nowamagic ();
  Print $nowamagic->nmmethod (). "<br/>";
  Print Article:: $nm. "<br/>";
  $nmArticle = new Article ();
  Print $nmArticle->nmmethod (). "<br/>";
? >

Program Run Result:

Www.nowamagic.net
Www.nowamagic.net
Www.nowamagic.net
Www.nowamagic.net

Program List: A simple static constructor

PHP does not have a static constructor, you may need to initialize the static class, there is a very simple way to invoke the demonstration () method of the class directly after the class definition.

<?php
Function Demonstration () {return ' This is the result of
  demonstration () ';
}
Class Mystaticclass
{
  //public static $MyStaticVar = demonstration ();//!!! Fails:syntax error public
  static $MyStaticVar = null;
  public static function Mystaticinit ()
  {
    //this are the static constructor
    //because in a function, Everythi Ng is allowed, including initializing using the other functions
    self:: $MyStaticVar = demonstration ();
  }
} Mystaticclass::mystaticinit (); Call the static constructor
Echo Mystaticclass:: $MyStaticVar;
This is the result of demonstration ()
?>

Program Run Result:

This is the result of demonstration ()

Here is a brief introduction to the use of PHP static variable static

The static keyword is very common in C # programming, and it is used to modifier declarations of static members that belong to the type itself and not to a particular object. The static modifier is available for classes, fields, methods, properties, operators, events, and constructors, but not for indexers, destructors, or types other than classes. Classes, functions, and variables declared as static will not be able to reference instance methods or variables, and in C # Once a class has been added a static modifier, all of its internal variables and methods must be static. Static variables and methods must be referenced through the class name and not through the instance object.

So what's the difference between the static keyword and C # in PHP?

Declaration scope

In the case of C #, the use of static variables in PHP is wider, we can not only add the static modifier to the class, method, or variable, we can even add the static keyword to the function's internal variables. A variable with the static modifier added even if the function completes the value is not lost, that is, the variable still remembers the original value the next time the function is called. Such as:

<?php
function Test ()
{
  static $var =;
  $var = =;
  echo $var. ';
}
Test ();
Test ();
Test ();
? >

The results of the operation are as follows:

3 5 7

One thing to note here is that the assignment of a variable is invoked only the first time the variable is initialized, and the operation is not invoked after the function is executed.

Because functions in PHP are also first-class citizens, unlike C #, we can directly define functions and invoke them directly anywhere in the code, which is similar to JavaScript. Therefore, the function static variable is more useful than defining the global variable, which avoids the conflicting definition of the variable. And since functions in C # cannot be directly defined and invoked, it must be hosted in a class, so if the function requires static variables, we only need to define them in the class to achieve the same effect.

Call mode

In C #, the way we call static members is very simple and consistent, because static members do not belong to instance objects, so whether it is a method or a variable, C # has access to its static members all through the class name. Method (variable). And in C #, static functions cannot be set to virtual methods or overwritten. PHP provides a more flexible and versatile support for this.

First, we know that the invocation instance method in PHP is called by Someobj->somefun (), so can we call the static function through Someclass->somefun () as C #? The answer is no, in PHP, the call to a static member can only be done by:: Someclass::somefun ().

<?php
class TESTC
{public
  static $var =;
  public $var =;
  function T ()
  {
    self:: $var = =;
    echo Self:: $var. ';
    echo $this->var. ';
  }
  public static function T ()
  {
    self:: $var = =;
    echo Self:: $var. ';
  }
}
$t =new TESTC ();
$t->t ();
Testc::t ();
? >

The results of the operation are as follows:

3 1 5

Another point that differs from C # is that in a method in a class, if we need to invoke a static variable, we must pass the self:: $somVar static variable (note the $ symbol before the variable, the instance variable is not needed), and the Calling static method Self::somefun () (No $ symbol is required). As in the previous example.

In addition, the biggest difference from C # is that in PHP, a subclass is a static function or variable that can overwrite a parent class, and not only that, (from a C # Programmer's Point of view, I think PHP does complicate things), because the default Self::staticfun () calls the static functions of subclasses , what if we want to invoke the static variables of the parent class? Here PHP provides additional parent to invoke the static members of the base class. Such as:

<?php
class TESTC
{public
  static $var =;
  public $var =;
  function T ()
  {
    self:: $var = =;
    echo Self:: $var. ';
    echo $this->var. ';
  }
  public static function T ()
  {
    self:: $var = =;
    echo Self:: $var. ';
  }
}
$t =new TESTC ();
$t->t ();
Testc::t ();
? >

The results of the operation are as follows:

3 5 ' Hello '

Best, according to the example above, it's easy to think that the subclass can access the parent keyword, so how does the parent class access the static method of the subclass? Here's another use for static, where if you change the scope of the call's static method to static, PHP calculates the final static method based on the class's inheritance hierarchy. Such as:

<?php
class Test
{
  function t ()
  {
    static::t ();
  }
  public static function T ()
  {
    echo self:: ' Test ';
  }
}
Class Test extends test
{
  static function T ()
  {
    echo self:: ' Test ';
  }
}
$t =new Test ();
$t->t ();
Test::t ();
? >

The results of the operation are as follows:

Test2 Test2

Here the T instance finds the final static method and outputs Test2 based on its instance when the T1 method calls the T2 static method.

Summarize

From the above analysis, it is not hard to see that PHP provides more powerful functionality or flexibility than C # for the use of static members, but from my perspective this flexibility is not necessarily better, and in some ways it may confuse me if the inheritance level of a class is too complex. Of course, the same tool can be used differently for different people, and since PHP offers a more diverse choice, it is believed that static in PHP may provide a more powerful and simpler way of using it than C #.

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.