?></td>
<td>
<code> The execution result is as follows:
1 |
Fatal error: Constructor test::test() cannot be static in /home/xxx/test.php on line 9 |
The constructor cannot be declared static, so the above inference is correct.
But this result is indeed very special, because maybe only PHP can statically call non-static methods. I did an experiment with Java. If you statically call a non-static method, the following error will be reported:
1
|
Cannot make a static reference to the non-static method showString() from the type HelloWorldApp |
I have not tried other languages one by one, but this is enough to illustrate the specialness of PHP However, I have not found any relevant explanation as to why PHP behaves like this.
2. Should static calls to non-static methods be applied?
So can we use this method instead of the static method? First of all, from the perspective of code readability, statically calling non-static methods is of course not recommended, which will make maintainers confused.
Next, let’s do some experiments to see if statically calling non-static methods has certain advantages in efficiency.
6 | for ( $k =0;
$k <10000; $k ++) { |
The execution of the above code here The time is 18 to 28 milliseconds. Let's test the standard writing method again.
3 | static function test2(){ } |
6 | for ( $k =0;
$k <10000; $k ++) { |
The above code execution time is 5 to 10 milliseconds. From this point of view, the efficiency of statically calling non-static methods is much lower than standard static method calls, so statically calling non-static methods is not recommended in terms of efficiency. I found that WordPress actually uses such a weird calling method:
class-wp.php Lines 206-207:
// Substitute the substring matches into the query. $query = addslashes(WP_MatchesMapRegex:: apply($query, $matches));
Static calling is used here, but the actual member function is not static.
Note: PHP cannot statically call non-static properties
4
|
function test2() {
|
Error: Access
The above introduces whether non-static methods can be called statically in PHP? (Weird call), including aspects of the content, I hope it will be helpful to friends who are interested in PHP tutorials.
|
|