谏知中文网

悟已往之不谏,知来者之可追

写PHP代码要注意的一些细节

发表于 2016-07-18 2299 次浏览

作为解释型语言,PHP代码的执行效率与代码结构密切相关,总结一些编码细节问题:

mt_rand()与rand()

mt_rand产生随机数的速率比用libc随机数发生器的rand快四倍

protected function randomFloat($min = 0, $max = 1) { 
                 return $min + mt_rand() / mt_getrandmax() * ($max - $min);  
 }

$this->randomFloat(1, 1.5);

protected function get_rand($length, $chars = '0123456789abcdefghijklmnopqrstuvwxyz') {
                    $hash = '';
                    $max = strlen($chars) - 1;
                    for($i=0; $i<$length; $i++) {
                              $hash .= $chars[mt_rand(0, $max)];
                     }
                     return $hash;
 }

$this->get_rand(23);

$_SERVER[REQUEST_TIME]与time()

request_time表示请求开始时的时间戳,time()通过函数返回当前Unix时间戳,要获取脚本执行时间,显然前者更高效

echo time().'/';
sleep(5);
echo $_SERVER['REQUEST_TIME'].'/';
echo time();

1469753270/1469753270/1469753275

strpos使用

strpos返回字符在查找字符串中首次出现的位置,如在字符串头部返回0,查找不存在则返回FALSE

$string = 'jyncode.com';
$search = 'jync';
$pos = strpos($string , $search) ;
if($pos === FALSE ) {
        echo $search.' is not found in '.$string;
} else {
    echo 'the position is '.$pos;
}

the position is 0

获取内存使用情况

memory_get_usage对比内存使用区别代码优劣情况,规避内存溢出,深入理解php内存回收机制

echo 'begin:'.memory_get_usage() .' bytes <br/>';
$i = 0;
while($i < 1000) {
        $arr[] = $i;
        $i++;
}
echo 'now:'.memory_get_usage() .' bytes <br/>';
unset($arr); //语言结构,无返回值
echo 'final:'.memory_get_usage() .' bytes <br/>';

begin:244520 bytes
now:381176 bytes
end:244656 bytes

我对GC垃圾回收机制的理解:
任何没有变量指向的对象都会当做是垃圾,将其在内存中销毁;当线程结束时,其占用所有内存空间将会被销毁,当前程序中所有对象也被销毁;GC进程根据Session开启和结束这个周期运行的

eval使用

$string = 'jyncode';
$pri_str = 'can you see this $string param';
echo $pri_str.'<br/>';

eval("\$pri_str_c = \"$pri_str\";");
echo $pri_str_c.'<br/>';
echo "can you see this $string param<br/>";

$arr_str = "array(
                'a' => 76,
                'b' => 96,
                'c' => 26
            );";
$arr = eval("return $arr_str;");
var_dump($arr);
can you see this $string param
can you see this jyncode param
can you see this jyncode param

array (size=3)
  'a' => int 76
  'b' => int 96
  'c' => int 26

可见eval用于字符串意义不大,可用来处理字符串形式的数组,建议数组入库前serialize处理会更方便

stream_context_create使用

$data = array ('resouse' => 'jyncode');
$data = http_build_query($data);

$opts = array (
'http' => array (
    'method' => 'POST',
    'content' => $data
  )
);

$context = stream_context_create($opts);
$html = file_get_contents('http://www.jyncode.com/index.php', false, $context);
echo $html;

设置http请求时相关的属性,包括超时时间、请求方式、头部信息、代理服务器等

static递归使用

函数中可定义静态变量,其生存周期会保持到程序执行完毕,而不是函数执行结束立即销毁,在此期间可当做缓存使用,static变量的作用域仅限于函数内声明处之后,常参与递归使用

function demo() {
    static $num = 1;
    echo $num;
    $num++;
    if($num <= 10) {
        demo();
    }
    
}

当然,除了定义static变量,使用函数传参的写法也能实现功能。