Home >Backend Development >PHP Tutorial >Analysis of efficiency issues of PHP static member functions
Many PHP developers know that using the staticmembersfunctionsof a class is more efficient than the ordinary member functions of the class. This article analyzes this problem from the application level
The following is an example:
<?php // php静态方法测试 header('Content-Type: text/html; charset=utf-8'); class xclass{ public static $var1 = '1111111111111111'; public $var2 = 'aaaaaaaaaaaaa'; public function construct() { $this -> var2 = 'bbbbbbbbbbbbbbbb'; } public static function secho1() { echo self :: $var1 . '<hr />'; } public function secho2() { echo $this -> var2 . '<hr />'; } public function secho3() { echo 'cccccccccccccc<hr />'; } } xclass :: secho1(); xclass :: secho3(); echo "------------------------------<br />"; $xc = new xclass(); $xc -> secho1(); $xc -> secho2(); ?>
If you look at the above example carefully, you will find an interesting point. After secho1() is defined as a static method, in the dynamic class For example, you can still reference as a dynamic method in the instance, and secho3() can also be used as a static member function. From this level, it is not difficult to understand why static member functions are faster than dynamic ones.
Perhaps due to compatibility reasons, PHP’s class members are not clearly distinguished between dynamic and static. All members will be treated as static members and stored in a specific memory area without explicit declaration. In , so calling a static member function is the same as calling a normal function, and it is very fast.
But calling a dynamic class is different. It uses this class structure as a sample to regenerate an object instance in the memory, so there is one more process, which is for a simple class , may not be a big deal, but for complex classes it obviously affects efficiency.
Some people worry about whether using static methods will cause excessive memory usage. In fact, from the above analysis, we can know that if you do not declare a static method, the system will still treat the members as static, so for a completely static method The memory occupied by a class is almost the same as that of a completely dynamic class that does not declare an instance object. Therefore, for more direct logic, it is recommended to directly use static member methods. Of course, some complex or obviously object-oriented ones For logic, it is not impossible to use static classes completely, but then the meaning of the class will be lost. If so, why bother with OOP? According to the purpose, static methods are especially suitable for logical classes in the MVC pattern.
The above is the detailed content of Analysis of efficiency issues of PHP static member functions. For more information, please follow other related articles on the PHP Chinese website!