php - PHP 的 __callStatic 与静态函数

标签 php

使用PHP的魔术函数__callStatic和正常定义静态函数在性能上有什么区别吗?

示例:

class Welcome{

 public static function __callStatic($method, $parameters){
   switch ($method) {
     case 'functionName1':
       // codes for functionName1 goes here
     break;
     case 'functionName2':
       // codes for functionName2 goes here
     break;
   }
 }

}

对比

class Welcome{

 public static function functionName1{
   //codes for functionName1 goes here
 }
 public static function functionName1{
   //codes for functionName1 goes here
 }

}

最佳答案

如果您只是谈论速度,那么这很容易测试:

class Testing
{
        private static $x = 0;

        public static function f1()
        {
                self::$x++;
        }
        public static function f2()
        {
                self::$x++;
        }
        public static function __callStatic($method, $params)
        {
                switch ($method) {
                        case 'f3':
                                self::$x++;
                                break;
                        case 'f4':
                                self::$x++;
                                break;
                }
        }
}

$start = microtime(true);
for ($i = 0; $i < 1000000; $i++) {
        Testing::f1();
        Testing::f2();
}
$totalForStaticMethods = microtime(true) - $start;

$start = microtime(true);
for ($i = 0; $i < 1000000; $i++) {
        Testing::f3();
        Testing::f4();
}
$totalForCallStatic = microtime(true) - $start;

printf(
    "static method: %.3f\n__callStatic: %.3f\n",
    $totalForStaticMethods,
    $totalForCallStatic
);

我得到static method: 0.187__callStatic: 0.812 ,因此定义实际方法的速度快了 4 倍以上。

我还想说使用__callStatic除非你有充分的理由,否则这种风格很糟糕。这使得跟踪代码变得更加困难,并且 IDE 更难提供自动完成功能。也就是说,在很多情况下这是值得的。

关于php - PHP 的 __callStatic 与静态函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31155382/

相关文章:

javascript - 如何在选择图像时直接上传图像而不是在 JQuery 中按上传按钮

php - 自动将 WordPress 帖子内容分成 3 列?

php - 如何在 PHP 中处理包含所需的类

javascript - 在javascript变量中存储PHP变量的值

php - 只选择不同的值 - MYSQL

php - 如何将此 MySQL 查询更改为从一个表而不是两个表中选择?

php - 如何在 PHP 和 MySQL 上使用循环?

php - APNS Push PHP 错误响应

PHP 自动将价格转换为 99 而不是 100

php - 使用 foreach 循环在 codeigniter 中添加 OR WHERE 语句