Several considerations for using static methods in PHP

  • 2021-07-18 07:41:42
  • OfStack

This paper introduces several common considerations for PHP to use static method. Share it for your reference. The specific methods are as follows:

1. Even if the method in the class is not declared with static, but it does not use changeable class member variables, it can still be called externally by the operator::;

2. The value of $this in a method called statically (using the:: operator) is determined by the context of the call! Instead of defining his class! !

For example, the following code:


<?php 
class TestClass1 
{ 
  public $normal_v = 'normal_v from TestClass1'; 
  public static $STATIC_V = 'STATIC_V from TestClass1'; 
  public function test_func1() 
  { 
    echo $this->normal_v.'<br />'.self::$STATIC_V; 
  } 
} 
class TestClass2 
{ 
  public $normal_v = 'normal_v from TestClass2'; 
  public static $STATIC_V = 'STATIC_V from TestClass2'; 
  public function test_func2() 
  { 
    TestClass1::test_func1(); 
  } 
} 
$t2 = new TestClass2(); 
$t2->test_func2(); 

What is the output of this code? I thought it would be normal_v from TestClass1 < br / > STATIC_V from TestClass1, the test found that I was wrong, and the correct output is:

normal_v from TestClass2
STATIC_V from TestClass1

Explanation: Although test_func1 () is defined in TestClass1, it is called in TestClass2, and its internal $this variable is determined by TestClass2!

In fact, the relationship between these two classes should belong to "two-way association".

Interested friends can test and run this example, and I believe there will be new gains!


Related articles: