• php


    个必须知道的实用

     PHP 

    函数和功能

    1

    、任意参数数目的函数

     

    你可能已经知道,

    PHP 

    允许定义可选参数的函数。

    但也有完全允许任意数目的函

    数参数的方法。以下是可选参数的例子:

     

    // function with 2 optional arguments 

    function foo($arg1 = '', $arg2 = '') { 

     

     

    echo "arg1: $arg1 "; 

     

    echo "arg2: $arg2 "; 

     

     

    foo('hello','world'); 

    /* prints: 

    arg1: hello 

    arg2: world 

    */ 

     

    foo(); 

    /* prints: 

    arg1: 

    arg2: 

    */ 

    现在让我们看看如何建立能够接受任何参数数目的函数。这一次需要使用

     

    func_get_args() 

    函数:

     

    // yes, the argument list can be empty 

    function foo() { 

     

     

    // returns an array of all passed arguments 

     

    $args = func_get_args(); 

     

     

    foreach ($args as $k => $v) { 

     

     

    echo "arg".($k+1).": $v "; 

     

     

     

    foo(); 

    /* prints nothing */

     

     
     
     

    */ 

    尽管脚本运行用了大约

     3 

    秒钟,

    CPU 

    使用率却非常非常低。因为在睡眠运行的

    过程中,该脚本实际上不消耗

     CPU 

    资源。还有许多其他的任务,可能需要一段

    时间,但不占用类似等待磁盘操作等

     CPU 

    时间。因此正如你所看到的,

    CPU 

    使

    用率和运行时间的实际长度并不总是相同的。下面是一个例子:

     

    // loop 10 million times (busy) 

    for($i=0;$i<10000000;$i++) { 

     

     

    $data = getrusage(); 

    echo "User time: ". 

     

    ($data['ru_utime.tv_sec'] + 

     

    $data['ru_utime.tv_usec'] / 1000000); 

    echo "System time: ". 

     

    ($data['ru_stime.tv_sec'] + 

     

    $data['ru_stime.tv_usec'] / 1000000); 

     

    /* prints 

    User time: 1.424592 

    System time: 0.004204 

    */ 

    这花了大约

     1.4 

    秒的

     CPU 

    时间,

    但几乎都是用户时间,

    因为没有系统调用。

    统时间是指花费在执行程序的系统调用时的

     CPU 

    开销。下面是一个例子:

     

    $start = microtime(true); 

    // keep calling microtime for about 3 seconds 

    while(microtime(true) - $start < 3) { 

     

     

    $data = getrusage(); 

    echo "User time: ". 

     

    ($data['ru_utime.tv_sec'] + 

     

    $data['ru_utime.tv_usec'] / 1000000); 

    echo "System time: ". 

     

    ($data['ru_stime.tv_sec'] + 

     

    $data['ru_stime.tv_usec'] / 1000000); 

     

    /* prints 

    User time: 1.088171 

    System time: 1.675315 

    */ 

    现在我们有相当多的系统时间占用。

    这是因为脚本多次调用

     microtime() 

    函数,

    该函数需要向操作系统发出请求,

    以获取所需时间。

    你也可能会注意到运行时间

    加起来不到

     3 

    秒。这是因为有可能在服务器上同时存在其他进程,并且脚本没

     100% 

    使用

     CPU 

    的整个

     3 

    秒持续时间。

     

    5

    、魔术常量

     

     

    PHP 

    提供了获取当前行号

     (__LINE__)

    、文件路径

     (__FILE__)

    、目录路径

     

    (__DIR__)

    函数名

     (__FUNCTION__)

    类名

     (__CLASS__)

    方法名

     (__METHOD__) 

    和命名空间

     (__NAMESPACE__) 

    等有用的魔术常量。

    在这篇文章中不作一一介绍,

    但是我将告诉你一些用例。

    当包含其他脚本文件时,

    使用

     __FILE__ 

    常量

    (或者

    使用

     PHP5.3 

    新具有的

     __DIR__ 

    常量):

     

    // this is relative to the loaded script's path 

    // 

    it 

    may 

    cause 

    problems 

    when 

    running 

    scripts 

    from 

    different 

    directories 

    require_once('config/database.php'); 

     

    // this is always relative to this file's path 

    // no matter where it was included from 

    require_once(dirname(__FILE__) . '/config/database.php'); 

    使用

     __LINE__ 

    使得调试更为轻松。你可以跟踪到具体行号。

     

    // some code 

    // ... 

    my_debug("some debug message", __LINE__); 

    /* prints 

    Line 4: some debug message 

    */ 

     

    // some more code 

    // ... 

    my_debug("another debug message", __LINE__); 

    /* prints 

    Line 11: another debug message 

    */ 

     

    function my_debug($msg, $line) { 

     

    echo "Line $line: $msg "; 

    6

    、生成唯一标识符

     

    某些场景下,

    可能需要生成一个唯一的字符串。

    我看到很多人使用

     md5() 

    函数,

    即使它并不完全意味着这个目的:

     

    // generate unique string 

    echo md5(time() . mt_rand(1,1000000)); 

    There is actually a PHP function named uniqid() that is meant to be used 

    for this. 

    // generate unique string 

    echo uniqid(); 

    /* prints 

    4bd67c947233e 

    */ 

     

    // generate another unique string 

    echo uniqid(); 

    /* prints 

    4bd67c9472340 

    */ 

    你可能会注意到,

    尽管字符串是唯一的,

    前几个字符却是类似的,

    这是因为生成

    的字符串与服务器时间相关。

    但实际上也存在友好的一方面,

    由于每个新生成的

     

    ID 

    会按字母顺序排列,这样排序就变得很简单。为了减少重复的概率,你可以

    传递一个前缀,或第二个参数来增加熵:

     

    // with prefix 

    echo uniqid('foo_'); 

    /* prints 

    foo_4bd67d6cd8b8f 

    */ 

     

    // with more entropy 

    echo uniqid('',true); 

    /* prints 

    4bd67d6cd8b926.12135106 

    */ 

     

    // both 

    echo uniqid('bar_',true); 

    /* prints 

    bar_4bd67da367b650.43684647 

    */ 

    这个函数将产生比

     md5() 

    更短的字符串,能节省一些空间。

     

     

    7

    、序列化

     

    你有没有遇到过需要在数据库或文本文件存储一个复杂变量的情况?你可能没

    能想出一个格式化字符串并转换成数组或对象的好方法,

    PHP 

    已经为你准备好此

    功能。有两种序列化变量的流行方法。下面是一个例子,使用

     serialize() 

     

    unserialize() 

    函数:

     

    // a complex array 

    $myvar = array( 

     

    'hello', 

     

    42, 

     

    array(1,'two'), 

     

    'apple' 

    ); 

     

    // convert to a string 

    $string = serialize($myvar); 

     

    echo $string; 

    /* prints 

    a:4:{i:0;s:5:"hello";i:1;i:42;i:2;a:2:{i:0;i:1;i:1;s:3:"two";}i:3;s:5

    :"apple";} 

    */ 

     

    // you can reproduce the original variable 

    $newvar = unserialize($string); 

     

    print_r($newvar); 

    /* prints 

    Array 

        [0] => hello 

        [1] => 42 

        [2] => Array 

            ( 

                [0] => 1 

                [1] => two 

            ) 

     

        [3] => apple 

    */ 

    这是原生的

     PHP 

    序列化方法。

    然而,

    由于

     JSON 

    近年来大受欢迎,

    PHP5.2 

    中已

    经加入了对

     JSON 

    格式的支持。现在你可以使用

     json_encode() 

     

    json_decode() 

    函数:

     

    // a complex array 

    $myvar = array( 

     

    'hello', 

     

    42, 

     

    array(1,'two'), 

     

    'apple' 

    ); 

     

    // convert to a string 

    $string = json_encode($myvar); 

     

    echo $string; 

    /* prints 

    ["hello",42,[1,"two"],"apple"] 

    */ 

     

    // you can reproduce the original variable 

    $newvar = json_decode($string); 

     

    print_r($newvar); 

    /* prints 

    Array 

        [0] => hello 

        [1] => 42 

        [2] => Array 

            ( 

                [0] => 1 

                [1] => two 

            ) 

     

        [3] => apple 

    */ 

    这将更为行之有效,

    尤其与

     JavaScript 

    等许多其他语言兼容。

    然而对于复杂的

    对象,某些信息可能会丢失。

     

    8

    、压缩字符串

     

    在谈到压缩时,

    我们通常想到文件压缩,

     ZIP 

    压缩等。

     PHP 

    中字符串压缩

    也是可能的,

    但不涉及任何压缩文件。

    在下面的例子中,

    我们要利用

     gzcompress() 

     gzuncompress() 

    函数:

     

    $string = 

    "Lorem ipsum dolor sit amet, consectetur 

    adipiscing elit. Nunc ut elit id mi ultricies 

    adipiscing. Nulla facilisi. Praesent pulvinar, 

    sapien vel feugiat vestibulum, nulla dui pretium orci, 

    non ultricies elit lacus quis ante. Lorem ipsum dolor 

    sit amet, consectetur adipiscing elit. Aliquam 

    pretium ullamcorper urna quis iaculis. Etiam ac massa 

    sed turpis tempor luctus. Curabitur sed nibh eu elit 

    mollis congue. Praesent ipsum diam, consectetur vitae 

    ornare a, aliquam a nunc. In id magna pellentesque 

    tellus posuere adipiscing. Sed non mi metus, at lacinia 

    augue. Sed magna nisi, ornare in mollis in, mollis 

    sed nunc. Etiam at justo in leo congue mollis. 

    Nullam in neque eget metus hendrerit scelerisque 

    eu non enim. Ut malesuada lacus eu nulla bibendum 

    id euismod urna sodales. "; 

     

    $compressed = gzcompress($string); 

     

    echo "Original size: ". strlen($string)." "; 

    /* prints 

    Original size: 800 

    */ 

     

    echo "Compressed size: ". strlen($compressed)." "; 

    /* prints 

    Compressed size: 418 

    */ 

     

    // getting it back 

    $original = gzuncompress($compressed); 

    这种操作的压缩率能达到

     50% 

    左右。另外的函数

     gzencode() 

     gzdecode() 

    能达到类似结果,通过使用不同的压缩算法。

     

    9

    、注册停止功能

     

    有一个函数叫做

     register_shutdown_function()

    ,可以让你在某段脚本完成运

    行之前,

    执行一些指定代码。

    假设你需要在脚本执行结束前捕获一些基准统计信

    息,例如运行的时间长度:

     

    // capture the start time 

    $start_time = microtime(true); 

     

    // do some stuff 

    // ... 

     

    // display how long the script took 

    echo "execution took: ". 

     

     

    (microtime(true) - $start_time). 

     

     

    " seconds."; 

    这似乎微不足道,

    你只需要在脚本运行的最后添加相关代码。

    但是如果你调用过

     

    exit() 

    函数,该代码将无法运行。此外,如果有一个致命的错误,或者脚本被

    用户意外终止,

    它可能无法再次运行。

    当你使用

     register_shutdown_function() 

    函数,代码将继续执行,不论脚本是否停止运行:

     

    $start_time = microtime(true); 

     

    register_shutdown_function('my_shutdown'); 

     

    // do some stuff 

    // ... 

     

    function my_shutdown() { 

     

    global $start_time; 

     

     

    echo "execution took: ". 

     

     

     

    (microtime(true) - $start_time). 

     

     

     

    " seconds."; 

    }

  • 相关阅读:
    JAVA 数据结构(16):SET(一)Java HashSet
    JAVA 数据结构(15):LIST(二)Java LinkedList
    PGSQL数据库里物化视图【materialized view】
    PGSQL存储过程学习
    PostgreSQL数据库结构
    javascript里面的document.getElementById
    odoo14学习----x2many操作与图片设置继承image.mixin
    odoo14在tree、kanban视图上添加dashboard
    odoo14在列表视图里添加自定义按钮
    python开发包之pyecharts
  • 原文地址:https://www.cnblogs.com/huzhen/p/3764830.html
Copyright © 2020-2023  润新知