Home > Article > Backend Development > Several notes on using static methods in PHP
This article mainly introduces several precautions for using static methods in PHP. It describes the skills and error-prone points of calling PHP static methods in the form of examples. It needs Friends can refer to
This articleInstance introduction several common precautions when using static methods in PHP. Share it with everyone for your reference. The specific method is 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 is still available externallyOperator :: to call ;
2. The value of $this in a method called statically (using the :: operator) is determined by the context of the call Determined! 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 will the output of this code be? I thought it would be normal_v from TestClass1 df250b2156c434f3390392d09b1c9563 STATIC_V from TestClass1, the test found that I was actually wrong, the correct output is:
normal_v from TestClass2
STATIC_V from TestClass1
Explanation: Although test_func1() is It is defined in TestClass1, but it is called in TestClass2. Its internal $this variable is determined by TestClass2!
In fact, the relationship between these two classes should be a "bidirectional association".
Interested friends can test and run the example of this article, I believe there will be new gains!
The above is the detailed content of Several notes on using static methods in PHP. For more information, please follow other related articles on the PHP Chinese website!