<?php
class Person{
public static $name = 'Voyager';
public static function say(){
echo 'My name is ' . self::$name;
}
}
1. Introduction
- No need to instantiate the class for direct access.
- There is only one copy in memory, which is shared by all instances.
- The access speed is faster than the instantiation access.
- Non-static properties and methods cannot be accessed in static methods (not yet created, the reason for the speed).
- Static properties cannot be accessed through instantiated objects, but static methods can.
- It cannot be directly defined as a variable or method, see 3 for details.
- After being defined, it will not be automatically recycled, see 4 for details.
2. Access method
Access static properties
Person::$name;
$me = new Person();
echo $me::$name;
Access static method
Person::say();
$me = new Person();
$me::say();
$me = new Person();
$me->say();//php7说静态调用非静态方法将被弃用
Three, initialize to an indefinite value
Why does static have an indefinite value? For example, a method that processes a batch of orders requires a random number or a timestamp for the start of the day. We need to initialize once, and then use this value for this batch of order processing, but the next batch is different.
<?php
class Person{
public static $age = 2018-1994;#正确
public static $number1 = self::$age; #错的
public static $number2 = mt_rand(18,24); #错的
public static $number3;
#正确
public static function init(){
if(!self::$number3){
self::$number3 = mt_rand(18,24);
}
}
#正确
public function __construct(){
if(!self::$number3){
self::$number3 = mt_rand(18,24);
}
}
}
// init
Person::init();
echo Person::$number3;
// __construct
$a = new Person();
$b = new Person();
echo $a::$number3;
echo '<br />';
echo $b::$number3;
Fourth, the static in the method
<?php
function increment1(){
static $n = 0;
$n++;
echo $n;
}
increment1(); #1
increment1(); #2
increment1(); #3
//输出‘123’
function increment2(){
$n = 0;
$n++;
echo $n;
}
increment2(); #1
increment2(); #1
increment2(); #1
//输出‘111’