Several precautions for using static methods in PHP
This article introduces several common precautions for 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 static, but it does not use changeable class member variables, it can still be called externally using the operator::;
2. The value of $this in a method called statically (using the :: operator) is determined by the context of the call! Not the class in which it is defined!!
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
|
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.' '.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();
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
19
20
21
|
<🎜>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.' '.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
STATIC_V from TestClass1. The test found that I was actually 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, and 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!
http://www.bkjia.com/PHPjc/879612.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/879612.htmlTechArticle Several precautions for using static methods in PHP. This article introduces several common precautions for using static methods in PHP. Share it with everyone for your reference. The specific method is as follows: 1. Even if the class...