Home >Backend Development >PHP Tutorial >Several precautions for using static methods in PHP, php static_PHP tutorial
The examples in this article introduce 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 static, but it does not use changeable class member variables, the operator:: can still be used externally to call ;
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:
<?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 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
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!
self:: means calling the static method get() in this class; because only static methods can be called in static methods, and instance methods cannot be called. If you call instance methods, use this,
PHP can currently use two methods, static class, which is just for convenience of calling without initializing the class.
But if your writing is wrong. Static classes lose the ability to be called statically.
Give me an example of a mistake.
2ab8e5b70df2b24c01d555d5ffc404ddhypnotize();
?>
Correct example
99bae946f7b29c47650561cb94eaefe2hypnotize();
?>