'const' vs. 'static' in PHP

You can use constants for default function argument values, where static variables are not allowed.


Another difference between const and static is that some variables like arrays are not allowed in class constants, so

class mytest
{
    public static $c = array(1=> 'hello', 2=>'world');
}

works, but

class mytest
{
    const c = array(1=> 'hello', 2=>'world');
}

won't.


The static variable can be changed, the const one cannot. The main consideration should be given to whether the config variables should be able to be altered at run time, not which is faster. The speed difference between the two (if there is any) is so minimal it isn't worth thinking about.


use function return global

0.0096, 0.0053, 0.0056, 0.0054, 0.0072, 0.0063, 0.006, 0.0054, 0.0054, 0.0055, 0.005, 0.0057, 0.0053, 0.0049, 0.0064, 0.0054, 0.0053, 0.0053, 0.0061, 0.0059, 0.0076, config1

use get instance normal class

0.0101, 0.0089, 0.0105, 0.0088, 0.0107, 0.0083, 0.0094, 0.0081, 0.0106, 0.0093, 0.0098, 0.0092, 0.009, 0.0087, 0.0087, 0.0093, 0.0095, 0.0101, 0.0086, 0.0088, 0.0082, config2

use static var

0.0029, 0.003, 0.003, 0.0029, 0.0029, 0.0029, 0.003, 0.0029, 0.003, 0.0031, 0.0032, 0.0031, 0.0029, 0.0029, 0.0029, 0.0029, 0.0031, 0.0029, 0.0029, 0.0029, 0.0029, config3

use const var 0.0033, 0.0031, 0.0031, 0.0031, 0.0031, 0.0031, 0.0032, 0.0031, 0.0031, 0.0031, 0.0031, 0.0034, 0.0031, 0.0031, 0.0033, 0.0031, 0.0037, 0.0031, 0.0031, 0.0032, 0.0031, config4

function getTime() { 
    $timer = explode( ' ', microtime() ); 
    $timer = $timer[1] + $timer[0]; 
    return $timer; 
}

$config["time"] = "time";

class testconfig2
{
    public  $time = "time";
    static $instance;
    static function getInstance()
    {
        if(!isset(self::$instance))
            self::$instance = new testconfig2();
        return self::$instance;
    }
}

class testconfig3
{
    static $time = "time";
}

class testconfig4
{
    const time = "time";
}

function getConfig1()
{
    global $config;
    return $config;
}

$burncount = 2000;
$bcount = 22;

for($lcnt =1;$lcnt < $bcount;$lcnt++){
$start = getTime(); 
for($i=1;$i< $burncount;$i++)
{
    $gs=getConfig1();
    $t = $gs["time"];
} 
$end = getTime(); 
echo  round($end - $start,4).', ';
}
echo  ' config1<br/>';



for($lcnt =1;$lcnt < $bcount;$lcnt++){
$start = getTime(); 
for($i=1;$i< $burncount;$i++)
{
    $gs=testconfig2::getInstance();
    $t = $gs->time;
} 
$end = getTime(); 
echo  round($end - $start,4).', ';
}
echo  ' config2<br/>';



for($lcnt =1;$lcnt < $bcount;$lcnt++){
$start = getTime(); 
for($i=1;$i< $burncount;$i++)
{
    $gs=testconfig3::$time;
    $t = $gs;
} 
$end = getTime(); 
echo  round($end - $start,4).', ';
}
echo  ' config3<br/>';



for($lcnt =1;$lcnt < $bcount;$lcnt++){
$start = getTime(); 
for($i=1;$i< $burncount;$i++)
{
    $gs=testconfig4::time;
    $t = $gs;
} 
$end = getTime(); 
echo  round($end - $start,4).', ';
}
echo  ' config4<br/>';
?>