PHP性能之语言性能优化:魔术方法好不好?

魔术方法是什么鬼?

  魔术方法,也叫魔鬼函数。只要学过PHP的都知道什么是魔术方法,魔术方法就是在某些条件下自动执行的函数。

  PHP的魔术方法主要有下面几个,其他的参考PHP官方手册

  

__construct() __destruct() __tostring() __invoke()
__call() __callStatic() __get() __set()
__isset() __unset __clone()  

  

为什么会有魔术方法?

  魔术方法是在需要实现一些功能,但是一般代码做不到或很难做到的时候才能用。

  比如 __construct(),其实该方法就是一个基本的方法,通过PHP内部的判断来运行该函数。也就是我们在初始化类的同时调用了一个函数,但是如果我们使用该方法,就多了PHP本身的一个判断的代码。

  再说 __get(),其实如果需要获取该变量的话,直接设置为public就行了,不能获取的变量就不能获取了,很简单。

  所以说,魔法方法是为了方(lan)便(ai),能不用魔术方法尽量不用。

 

魔术方法性能测试(__get())

  使用__get()的代码示例

 1 <?php 
 2 
 3 /**
 4 * 测试类
 5 */
 6 class test
 7 {
 8     private $name = "jepeng";
 9 
10     public function __get($varname)
11     {
12         return $this->name;
13     }
14 }
15 
16 $i = 0;
17 
18 while ( $i<= 10000) {
19     $i++;
20     $test = new test();
21     $test->name;
22 }

  正常代码示例

 1 <?php 
 2 
 3 /**
 4 * 测试类
 5 */
 6 class test
 7 {
 8     public $name = "jepeng";
 9 }
10 
11 $i = 0;
12 
13 while ( $i<= 10000) {
14     $i++;
15     $test = new test();
16     $test->name;
17 }

测试结果:

  一万次循环 十万次循环
__get() 21ms 106ms
正常 17ms 41ms


  结论:

  两种方法少循环相差不到,到了十万级的循环,结果是成倍数增加。所以能不用魔术方法尽量不用魔术方法

  文章为作者学习所得,有纰漏,请留言指出,谢谢支持!转载请附上本文章的连接

原文地址:https://www.cnblogs.com/miao-zp/p/6373180.html