PHP static

<?php
class Person{
    
    
	public static $name = 'Voyager';
	public static function say(){
    
    
		echo 'My name is ' . self::$name;
	}
}

1. Introduction

  1. No need to instantiate the class for direct access.
  2. There is only one copy in memory, which is shared by all instances.
  3. The access speed is faster than the instantiation access.
  4. Non-static properties and methods cannot be accessed in static methods (not yet created, the reason for the speed).
  5. Static properties cannot be accessed through instantiated objects, but static methods can.
  6. It cannot be directly defined as a variable or method, see 3 for details.
  7. After being defined, it will not be automatically recycled, see 4 for details.

2. Access method

Access static properties
  1. Person::$name;
  2. $me = new Person();
    echo $me::$name;
Access static method
  1. Person::say();
  2. $me = new Person();
    $me::say();
  3. $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’

Guess you like

Origin blog.csdn.net/z772532526/article/details/83375629