Is there are any performance difference between using PHP's magic function __callStatic and defining static function normally.
Example:
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;
}
}
}
vs
class Welcome{
public static function functionName1{
//codes for functionName1 goes here
}
public static function functionName1{
//codes for functionName1 goes here
}
}
If you're just talking about speed, this is easy enough to test:
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
__callStatic: %.3f
",
$totalForStaticMethods,
$totalForCallStatic
);
I get static method: 0.187
and __callStatic: 0.812
, so defining actual methods is over 4 times faster.
I would also say that using __callStatic
is bad style unless you have a good reason for it. It makes it harder to trace code, and IDEs have a harder time providing auto-complete features. That said, there are plenty of cases where it's worth it.