PHP static static detailed explanation

foreword

Both PHP class properties and methods need to be called after the class is instantiated (except for constant properties). However, PHP also provides static properties and static methods. The so-called "static" means that you can call directly without instantiating the class these properties and methods. Static classes are not impossible to instantiate, but can be used without instantiation.

Definition of static members

Use the static keyword to modify the properties and methods of the class, and call these properties and methods static properties and static methods.

1. Static attributes

grammar:

static 属性名

Example:

<?php
class Foo {
  public static $my_static = 'hello';  
}
?>

2. Static method

grammar:

static function 方法名{
    //代码
}

Example:

<?php
class Foo {
  public static function staticValue() {
     return 'hello';
  }
}
?>

Note: Static properties and methods, like object properties and methods, support setting private, protected, publicthree visibility levels.

static member call

1. Call static properties/methods outside the class

类名::属性/方法 Called by .

<?php
class Mystatic {
  public static $staticvalue = 'zhangsan';
  public static function staticMethod() {
    $a = 'hello';
    return $a;
  }
}
echo '$staticvalue: '.Mystatic::$staticvalue.PHP_EOL;
echo '$a: '.Mystatic::staticMethod().PHP_EOL;
?>

Note: The predefined constant PHP_EOLrepresents the system newline character.

result:

$staticvalue: zhangsan
$a: hello

对象名::属性/方法 Called by .

<?php
class Mystatic {
  public static $staticvalue = 'zhangsan';
  public static function staticMethod() {
    $a = 'hello';
    return $a;
  }
}
$obj = new Mystatic();
echo '$staticvalue: '.$obj::$staticvalue.PHP_EOL;
echo '$a: '.$obj::staticMethod();
?>

result:

$staticvalue: zhangsan
$a: hello

By 对象名 -> 方法calling, 对象名 -> 属性it will fail.

<?php
error_reporting(0);
class Mystatic {
  public static $staticvalue = 'zhangsan';
  public static function staticMethod() {
    $a = 'hello';
    return $a;
  }
}
$obj = new Mystatic();
echo '$staticvalue: '.$obj -> staticvalue.PHP_EOL;
echo '$a: '.$obj -> staticMethod();
?>

result:

$staticvalue:
$a: hello

2. Call static properties/methods in non-static methods

Called by , self points to the current class , just like $this points to the current object; and in the case of no instantiation, the pointer points to an empty object , so it cannot be touched to refer to static properties and methods. self::属性/方法$this

<?php
class Mystatic {
  public static $staticvalue = 'zhangsan';
  public static function staticMethod() {
    $a = 'hello';
    return $a;
  }
  public function noStatic(){
    echo '$staticvalue: '.self::$staticvalue.PHP_EOL;
    echo '$a: '.self::staticMethod();

  }
}
$obj = new Mystatic();
$obj -> noStatic();
?>

result:

$staticvalue: zhangsan
$a: hello

3. Call static properties/methods in static methods

Same as calling a static property/method in a non-static method.

<?php
class Mystatic {
  public static $staticvalue = 'zhangsan';
  public static function staticMethod1() {
    $a = 'hello';
    return $a;
  }
  public static function staticMethod2(){
    echo '$staticvalue: '.self::$staticvalue.PHP_EOL;
    echo '$a: '.self::staticMethod1().PHP_EOL;

  }
}
Mystatic::staticMethod2();
$obj = new Mystatic();
$obj -> staticMethod2();
?>

result:

$staticvalue: zhangsan
$a: hello
$staticvalue: zhangsan
$a: hello

4. Call the static property/method of another class

If you call the static properties and methods of other classes in a class, you need to reference them. 完整类名::

<?php
class Mystatic1 {
  public static $staticvalue1 = 'xiaomin';
}
class Mystatic2 {
  public static $staticvalue2 = 'zhangsan';
  public static function staticMethod() {
    echo '$staticvalue1: '.Mystatic1::$staticvalue1.PHP_EOL;
    echo '$staticvalue2: '.self::$staticvalue2.PHP_EOL;

  }
}
Mystatic2::staticMethod();
$obj = new Mystatic2();
$obj -> staticMethod();
?>

result:

$staticvalue1: xiaomin
$staticvalue2: zhangsan
$staticvalue1: xiaomin
$staticvalue2: zhangsan

5. Static properties/methods of calls privateand protectedvisibility levels

Due to privatethe protectedlimitation of attributes, it can only be called within the class. If you want to call it outside the class, you need to provide a publicmethod, method access private, and protectedattribute for the outside. Terminology: A class provides an interface to the outside world.

<?php
class Mystatic {
  public static $staticvalue1 = 'zhangsan';
  private static $staticvalue2 = 20;
  protected static $staticvalue3 = 'student';
  private static function staticMethod() {
    $a = 'hello';
    return $a;
  }
  public function port1() {
    echo '$staticvalue1: '.self::$staticvalue1.PHP_EOL;
    echo '$staticvalue2: '.self::$staticvalue2.PHP_EOL;
    echo '$staticvalue3: '.self::$staticvalue3.PHP_EOL;
    echo '$a: '.self::staticMethod().PHP_EOL;
  }
  public static function port2() {
    echo '$staticvalue1: '.self::$staticvalue1.PHP_EOL;
    echo '$staticvalue2: '.self::$staticvalue2.PHP_EOL;
    echo '$staticvalue3: '.self::$staticvalue3.PHP_EOL;
    echo '$a: '.self::staticMethod().PHP_EOL;
  }
}
$obj = new Mystatic();
$obj -> port1();
echo "\r\n";
Mystatic::port2();
?>

result:

$staticvalue1: zhangsan
$staticvalue2: 20
$staticvalue3: student
$a: hello

$staticvalue1: zhangsan
$staticvalue2: 20
$staticvalue3: student
$a: hello

Static attributes support dynamic modification

In practical applications, there will be multiple objects of a class that may share a piece of data. Both class constants and static properties can be implemented. Static properties are similar (same) to class constants, the only difference is that class constants cannot be changed, while static properties can be changed. The access method is the same, both can use ::access. Static properties need to add $, there is no $ before the constant name, so there is no need to add it when accessing class constants.

1. Class constants

<?php
class Myconst {
  const A = 1234;
}
$obj1 = new Myconst();
echo 'A: '.$obj1::A.PHP_EOL;
$obj1->A='aaa';
//$obj1::A='aaa';会报错
echo "\r\n";
$obj2 = new Myconst();
echo 'A: '.$obj2::A.PHP_EOL;
?>

result:

A: 1234

A: 1234

2. Static attributes

<?php
class Mystatic {
  public static $A = 1234;
}
echo '$A: '.Mystatic::$A.PHP_EOL;
Mystatic::$A = 6666;
echo '$A: '.Mystatic::$A.PHP_EOL;
$obj1 = new Mystatic();
echo '$A: '.$obj1::$A.PHP_EOL;
Mystatic::$A = 5555;
$obj2 = new Mystatic();
echo '$A: '.$obj2::$A.PHP_EOL;
echo '$A: '.$obj1::$A.PHP_EOL;
?>

result:

$A: 1234
$A: 6666
$A: 6666
$A: 5555
$A: 5555

Inheritance and Overriding of Static Members

Like non-static properties/methods, static properties and methods can also be inherited by subclasses, and static properties and methods can also be overridden by subclasses.

1. Static attributes

Subclasses can rewrite the static member variables of the parent class, but the static variables of the parent class still exist. These two static member variables are independent. They will be accessed separately according to the class name of the call.

<?php
class Mystatic
{
    static public $a;           //定义一个静态变量
    static function test()        //定义静态方法来操作并输出静态变量
    {
        self::$a++;
        return self::$a;
    }
}
class Mystatic2 extends  Mystatic          //定义一个子类
{
    static function test()           //定义子类的静态方法
    {
        self::$a++;                 //访问并操作父类的静态变量
        return self::$a;
    }
}
$obj1=new Mystatic;                              //新建父类对象
echo '此时$a的值为: '.$obj1->test().PHP_EOL;     //通过对象调用静态方法test,静态属性$a的值+1
$obj2=new Mystatic;                              //新建另一个父类对象
echo '此时$a的值为: '.$obj2->test().PHP_EOL;     //新父类对象调用静态方法test,静态属性$a的值+1+1
$obj3=new Mystatic2;                             //新建子类对象
echo '此时$a的值为: '.$obj3->test().PHP_EOL;     //子类对象调用同名静态方法test, 静态属性$a的值+1+1+1
echo Mystatic::$a.PHP_EOL;    //通过父类::直接访问静态成员$a变量
echo $obj1::$a.PHP_EOL;   //通过对象名::可以直接访问静态成员$a变量
?>

result:

此时$a的值为: 1
此时$a的值为: 2
此时$a的值为: 3
3
3

2. Static method

Subclasses can override static methods of parent classes.

<?php
class Mystatic1 {
    public static function getclassName() {
        return __CLASS__;
    }

    public static function whoclassName() {
        echo self::getclassName().PHP_EOL;
    }
}

class Mystatic2 extends Mystatic1{
    public static function getclassName() {
        return __CLASS__;
    }
}

echo Mystatic1::getclassName().PHP_EOL;
echo Mystatic2::getclassName().PHP_EOL;
?>

__CLASS__The class name of the current class can be obtained through , and we call getClassNamethe methods of the two classes respectively:

result:

Mystatic1
Mystatic2

It shows that the subclass overrides the static method with the same name of the parent class, and we can also call whoclassNamethe method :

<?php
class Mystatic1 {
    public static function getclassName() {
        return __CLASS__;
    }

    public static function whoclassName() {
        echo self::getclassName().PHP_EOL;
    }
}

class Mystatic2 extends Mystatic1{
    public static function getclassName() {
        return __CLASS__;
    }
}

echo Mystatic1::whoclassName();
echo Mystatic2::whoclassName();
?>

result:

Mystatic1
Mystatic1

Why is the result of the second print the parent class Mystatic1name instead of the subclass name Mystatic2? This is because $thisthe pointer always points to the reference object that holds it, but selfnot 定义时持有它的类to . In order to solve this problem, starting from PHP 5.3, a new feature called delayed static binding调用时的类 has been added .

Lazy static binding

Late Static Bindings (Late Static Bindings) is aimed at the invocation of static methods. When using this feature, the static method is no longer self:: referenced but passed . If it is called in the class that defines it, then, at this time, it is the same as the function . If it is called in a subclass or other class, point to it . static::指向当前类self调用该方法所在的类

<?php
class Mystatic1 {
    public static function getclassName() {
        return __CLASS__;
    }

    public static function whoclassName() {
        echo static::getclassName().PHP_EOL;
    }
}

class Mystatic2 extends Mystatic1{
    //self改为static
    public static function getclassName() {
        return __CLASS__;
    }
}
echo Mystatic1::whoclassName();
echo Mystatic2::whoclassName();
?>

result:

Mystatic1
Mystatic2

Indicates that the late static binding takes effect, that is, it staticpoints to the class where the method calling it is located, not when it is defined, so it is called delayed static binding.

In addition, you can also use static::classto point to the class name of the current calling class, for example, we can use it instead __CLASS__, so that the above subclasses do not need to rewrite getClassNamethe method :

<?php
class Mystatic1 {
    public static function getclassName() {
        return static::class;
    }

    public static function whoclassName() {
        echo static::getclassName().PHP_EOL;
    }
}

class Mystatic2 extends Mystatic1{}

echo Mystatic1::getclassName().PHP_EOL;
echo Mystatic2::getclassName().PHP_EOL;
echo Mystatic1::whoclassName();
echo Mystatic2::whoclassName();
?>

result:

Mystatic1
Mystatic2
Mystatic1
Mystatic2

In the same way, self::classit always points to the class that defines it.

The difference between static and non-static

  • Static properties and methods can be directly referenced by the class, so they are also called class properties and class methods. Non-static properties and non-static methods need to be referenced by the object after instantiation, so they are called object properties and object methods.

  • Static attributes are stored in the class space, and non-static attributes are stored in the object space. Non-static methods can access any member of the class (including static), and static methods can only access static members of the class.

  • Static methods can be called directly, class name calls and object calls ( 类名或self::calls), but non-static methods can only be called ( 对象名或$this->calls) through objects.

  • All instance objects of a class share the static properties in the class. If this class static property is modified, then all objects of this class can access this new value.

  • The life cycle of static methods and properties is as long as the corresponding class, and static methods and static properties will be allocated and loaded into memory along with the definition of the class. Static properties and methods are not destroyed until the thread ends. The life cycle of non-static methods and properties is as long as the instantiated object of the class. Only when the class instantiates an object, the non-static methods and properties will be created, and when the object is destroyed, the non-static method will be destroyed immediately. destroy. Static methods and static variables always use the same block of memory after creation, while using instances will create multiple memories. However, static methods are more efficient than instantiation. The disadvantage of static methods is that they are not automatically destroyed, while instantiated ones can be destroyed.

Application scenario:

  1. Static methods are most suitable for the definition of methods in tool classes; such as file operations, date processing methods, etc.

  2. Static variables are suitable for the definition of global variables.

Reference link:

PHP static properties and static methods | object-oriented programming | PHP entry to actual combat tutorial

https://www.jb51.net/article/110708.htm

The Secret of PHP Classes (4) Static Properties and Static Methods - Nuggets

The difference between static methods and non-static methods - kittyUncle - 博客园

Guess you like

Origin blog.csdn.net/WHQ556677/article/details/122356593