Considerations for using static methods in PHP
This article introduces several common precautions for using static methods in PHP. Share it with you for your reference. The specific method is as follows:
1. Even if the methods in the class are not declared as static, but they do not use variable members of the changeable class, they can still be called using the external operator;
2. The value of $ this in the method called in static mode (with: Operator) is determined by the context during the call! Instead of defining its class !!
For example, the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<? 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 showed that I was wrong. The correct output is:
Normal_v from TestClass2
STATIC_V from TestClass1
Note: Although test_func1 () is defined in TestClass1, it is called in TestClass2. The internal $ this variable is determined by TestClass2!
In fact, the relationship between these two classes should belong to "two-way Association ".
If you are interested, you can test and run this article. I believe there will be new gains!