[Base] php static and non-static variables, methods

Static variables or functions are stored in static memory, will be released only to the end of the program, he was assigned when it

 

If the class is called once, at compile time static class need to do more work in the implementation of dynamic class needs a bit more work, but php is dynamic language, every time these two steps is not out, so to run only once the class , it does not matter who fast who slow.

 

However, if a class in a program which is not the same for multiple calls, static class assignment is a compile time, run after the program can be called up directly, rather than dynamically allocated memory, and it saves time, the reason why the analogy fast static dynamic class (the premise is called many times to remember).

class A
{

  public static $a;

  public $b;

  public function __construct($a=1,$b=2)
  {
    self::$a = $a;
    $this->$b = $b;
  }

  public static function func_static()
  {
    echo 'func_static'.PHP_EOL;

    $ this- echo> b; // error, can not use the $ this keyword, you can not call

    echo self :: $ a // normal

  }

  public function func()
  {
    echo 'func'.PHP_EOL;

  }  

}

A :: func_static (); // normal

A :: func () // error

$obj = new A();

$ Obj -> func (); // normal

to sum up:

  1. statically declared using the static keyword

  2. static variable or a static method call need not instantiate the class 

  3 . Call static variable in the class using self :: 

  4. You can not use the keyword $ this in a static method  

 

 

 

 

Guess you like

Origin www.cnblogs.com/baboben/p/12032611.html