zoukankan      html  css  js  c++  java
  • 你应该知道的9个强大的PHP函数

    包括:强大的文件查找功能,收集内存使用信息,生成唯一ID,序列化,压缩字符串,CPU使用信息等。
    U
    sing the right code at the right time, it can absolutely speed up your web development progress. Today, I have complied 9 really awesome PHP functions and features that you should be familiar with. Hope , it will be helpful in your forthcoming developments.

    1) Functions with Arbitrary Number of Arguments

    You may already know that PHP allow you to define functions with optional arguments. However, here I am going to show you a method for allowing completely arbitrary number of function arguments.

    Here is an example with optional arguments:

    01 // function with 2 optional arguments
    02 function my_function($parameter1 = '', $parameter2 = '') {
    03  
    04      echo "parameter1: $parameter1\n";
    05      echo "parameter2: $parameter2\n";
    06 }
    07  
    08 foo('hello','anson cheung');
    09 /* prints:
    10 parameter1: hello
    11 parameter2: anson cheung
    12 */
    13 foo();
    14 /* prints:
    15 parameter1:
    16 parameter2:
    17 */

    Well, I am going to use func_get_args() to demonstrate you how we can build a function that accepts any number of arguments:

    01 // The argument list can be empty
    02 function my_function() {
    03  
    04       // returns an array of all passed arguments
    05      $parameters = func_get_args();
    06      foreach ($parameters as $key => $value) {
    07        echo "parameter".($parameter+1).": $value\n";
    08      }
    09  
    10 }
    11 //Example 1
    12 foo();
    13 /* prints nothing */
    14  
    15  
    16 //Example 2
    17 foo('hello');
    18 /* prints
    19 parameter1: hello
    20 */
    21  
    22 //Example 3
    23 foo('hello', 'I am ', 'anson cheung');
    24 /* prints
    25 parameter1: hello
    26 parameter2: I am
    27 parameter3: anson cheung
    28 */

    2) Powerful function to Find Files

    When we talking about file searching, a lot of programmer would think of scandir() function. However, here I am going to introduce you more capable version of the scandir() function. The glob()can let you search for files by using patterns.

    Example1: Get all of php files:

    01 $files = glob('*.php');
    02  
    03 print_r($files);
    04  
    05 /* output looks like:
    06 Array
    07 (
    08     [0] => phptesting.php
    09     [1] => ptest.php
    10     [2] => post_output.php
    11     [3] => testing.php
    12 )
    13 */

    Example 2: Fetch multiple file types:

    01 $files = glob('*.{php,txt}', GLOB_BRACE);
    02  
    03 print_r($files);
    04  
    05 /* output looks like:
    06 Array
    07 (
    08     [0] => phptesting.php
    09     [1] => ptest.php
    10     [2] => post_output.php
    11     [3] => testing.php
    12     [4] => log_file.txt
    13     [5] => test_2011.txt
    14 )
    15 */

    Example 3: Return files with a path:

    01 $files = glob('../images/b*.jpg');
    02  
    03 print_r($files);
    04  
    05 /* output looks like:
    06 Array
    07 (
    08     [0] => ../images/baby.jpg
    09     [1] => ../images/babyboy.jpg
    10 )
    11 */

    Example 4: If you want to full path of each file, you can just call the realpath() function on the returned values:

    01 $files = glob('../images/a*.jpg');
    02  
    03  
    04 // applies the function to each array element
    05 $files = array_map('realpath',$files);
    06 print_r($files);
    07  
    08 /* output looks like:
    09 Array
    10 (
    11     [0] => C:\xampp\www\images\angry.jpg
    12     [1] => C:\xampp\www\images\ajax.jpg
    13 )
    14 */

    3) Memory usage information

    PHP has a garbage collector and a very powerful, complex memory manager. Hence, the amount of memory being consumed by you script would be go up and down during execution of script. If a function could return you the memory usage of your script, we can better optimize your code better.

    To get current memory usage, we can use the memory_get_usage() function; If you want to know the highest amount of memory used at any point, we can call the memory_get_peak_usage() function.

    01 echo "Initial: ".memory_get_usage()." bytes \n";
    02 /* prints
    03 Initial: 361400 bytes
    04 */
    05  
    06 // let's use up some memory
    07 for ($i = 0; $i < 100000; $i++) {
    08 $array []= md5($i);
    09 }
    10 // let's remove half of the array
    11 for ($i = 0; $i < 100000; $i++) {
    12 unset($array[$i]);
    13 }
    14  
    15 echo "Final: ".memory_get_usage()." bytes \n";
    16 /* prints
    17 Final: 885912 bytes
    18 */
    19 echo "Peak: ".memory_get_peak_usage()." bytes \n";
    20 /* prints
    21 Peak: 13687072 bytes
    22 */

    4) Magic Constant

    PHP provides useful magic constants for fetching the current line number (__LINE__), file path (__FILE__), directory path (__DIR__), function name (__FUNCTION__), class name (__CLASS__), method name (__METHOD__) and namespace (__NAMESPACE__).

    01 // some code
    02 // ...
    03 my_debug("some debug message", __LINE__);
    04 /* prints
    05 Line 4: some debug message
    06 */
    07  
    08 // some more code
    09 // ...
    10 my_debug("another debug message", __LINE__);
    11 /* prints
    12 Line 11: another debug message
    13 */
    14 function my_debug($msg, $line) {
    15 echo "Line $line: $msg\n";
    16 }

    5) Generating Unique ID

    In many situation, we need to generate a unique string. However, I have seen many programmer using various method to achieve. Some people use md5(); however, it is not exactly meant for this purpose.

    01 // generate unique string
    02 echo md5(time() . mt_rand(1,1000000));
    03  
    04 In PHP, there is a function named as uniqid() that is meant to be used for this.
    05 // generate unique string
    06 echo uniqid();
    07 /* prints
    08 4bd67c947233e
    09 */
    10  
    11 // generate another unique string
    12 echo uniqid();
    13 /* prints
    14 4bd67c9472340
    15 */

    You may noticed that the strings are unique, but they are seems similar for the several characters. This is because the generated string is related to the server time.

    To generate a much random string, we can pass a prefix, or the second parameter to increase entropy:

    01 // with prefix
    02 echo uniqid('foo_');
    03 /* prints
    04 foo_4bd67d6cd8b8f
    05 */
    06  
    07 // with more entropy
    08 echo uniqid('',true);
    09 /* prints
    10 4bd67d6cd8b926.12135106
    11 */
    12 // both
    13 echo uniqid('bar_',true);
    14 /* prints
    15 bar_4bd67da367b650.43684647
    16 */

    6. Serialization

    When you need to store a complex variable into database or text file, some people may write their own solution to convert arrays or objects into formatted strings. However, there are PHP build functions available.

    There are two popular methods of serializing variables. Here is an example that uses the serialize() and unserialize():

    01 // a complex array
    02 $myvar = array(
    03 'hello',
    04 42,
    05 array(1,'two'),
    06 'apple'
    07 );
    08  
    09 // convert to a string
    10 $string = serialize($myvar);
    11 echo $string;
    12 /* prints
    13 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";}
    14 */
    15  
    16 // you can reproduce the original variable
    17 $newvar = unserialize($string);
    18 print_r($newvar);
    19 /* prints
    20 Array
    21 (
    22     [0] => hello
    23     [1] => 42
    24     [2] => Array
    25         (
    26             [0] => 1
    27             [1] => two
    28         )
    29  
    30     [3] => apple
    31 )
    32 */

    Other than native PHP serialization method, there is an alternative way to do it in recent years. Start from PHP 5.2, JSON are supported and there are two corresponding function as well.Now you can use the json_encode() and json_decode() functions as well:

    01 // a complex array
    02 $myvar = array(
    03 'hello',
    04 42,
    05 array(1,'two'),
    06 'apple'
    07 );
    08  
    09 // convert to a string
    10 $string = json_encode($myvar);
    11 echo $string;
    12 /* prints
    13 ["hello",42,[1,"two"],"apple"]
    14 */
    15  
    16 // you can reproduce the original variable
    17 $newvar = json_decode($string);
    18 print_r($newvar);
    19 /* prints
    20 Array
    21 (
    22     [0] => hello
    23     [1] => 42
    24     [2] => Array
    25         (
    26             [0] => 1
    27             [1] => two
    28         )
    29  
    30     [3] => apple
    31 )
    32 */

    7) Compressing Strings

    When talking about compression, we may think about file compression by using ZIP, tar...etc.However, it is possible to compress long strings in PHP without using any archive files.

    Here, I am going to illustrate an example on using gzcompress() and gzuncompress() functions:

    01 $string =
    02 "Lorem ipsum dolor sit amet, consectetur
    03 adipiscing elit. Nunc ut elit id mi ultricies
    04 adipiscing. Nulla facilisi. Praesent pulvinar,
    05 sapien vel feugiat vestibulum, nulla dui pretium orci,
    06 non ultricies elit lacus quis ante. Lorem ipsum dolor
    07 sit amet, consectetur adipiscing elit. Aliquam
    08 pretium ullamcorper urna quis iaculis. Etiam ac massa
    09 sed turpis tempor luctus. Curabitur sed nibh eu elit
    10 mollis congue. Praesent ipsum diam, consectetur vitae
    11 ornare a, aliquam a nunc. In id magna pellentesque
    12 tellus posuere adipiscing. Sed non mi metus, at lacinia
    13 augue. Sed magna nisi, ornare in mollis in, mollis
    14 sed nunc. Etiam at justo in leo congue mollis.
    15 Nullam in neque eget metus hendrerit scelerisque
    16 eu non enim. Ut malesuada lacus eu nulla bibendum
    17 id euismod urna sodales. ";
    18  
    19 $compressed = gzcompress($string);
    20 echo "Original size: ". strlen($string)."\n";
    21 /* prints
    22 Original size: 800
    23 */
    24  
    25 echo "Compressed size: ". strlen($compressed)."\n";
    26 /* prints
    27 Compressed size: 418
    28 */
    29 // getting it back
    30 $original = gzuncompress($compressed);

    Other than gzcompress() and gzuncompress() functions, we can use gzencode() and gzdecode() to archive similar result.

    8) Register Shutdown Function

    There is a function called register_shutdown_function(), which will let you execute some code right before the script finishes running. Imagine that you want to capture some benchmark statistics at the end of your script execution, such as how long it took to run:

    1 // capture the start time
    2 $start_time = microtime(true);
    3  
    4 // do some stuff
    5 // ...
    6 // display how long the script took
    7 echo "execution took: ".
    8   (microtime(true) - $start_time).
    9   " seconds.";

    At first this may seem trivial. You just add the code to the very bottom of the script and it runs before it finishes. However, if you ever call the exit() function, that code will never run. Also, if there is a fatal error, or if the script is terminated by the user (by pressing the Stop button in the browser), again it may not run. When you use register_shutdown_function(), your code will execute no matter why the script has stopped running:

    01 $start_time = microtime(true);
    02  
    03 register_shutdown_function('my_shutdown');
    04 // do some stuff
    05 // ...
    06  
    07 function my_shutdown() {
    08 global $start_time;
    09 echo "execution took: ".
    10    (microtime(true) - $start_time).
    11    " seconds.";
    12 }

    9) CPU Usage Information

    For this, we are going to utilize the getrusage() function. Keep in mind that this is not available on Windows platforms

    01 print_r(getrusage());
    02 /* prints
    03 Array
    04 (
    05     [ru_oublock] => 0
    06     [ru_inblock] => 0
    07     [ru_msgsnd] => 2
    08     [ru_msgrcv] => 3
    09     [ru_maxrss] => 12692
    10     [ru_ixrss] => 764
    11     [ru_idrss] => 3864
    12     [ru_minflt] => 94
    13     [ru_majflt] => 0
    14     [ru_nsignals] => 1
    15     [ru_nvcsw] => 67
    16     [ru_nivcsw] => 4
    17     [ru_nswap] => 0
    18     [ru_utime.tv_usec] => 0
    19     [ru_utime.tv_sec] => 0
    20     [ru_stime.tv_usec] => 6269
    21     [ru_stime.tv_sec] => 0
    22 )
    23  
    24 */

    That may look a bit cryptic unless you already have a system administration background. Here is the explanation of each value (you don't need to memorize these):

    • ru_oublock: block output operations
    • ru_inblock: block input operations
    • ru_msgsnd: messages sent
    • ru_msgrcv: messages received
    • ru_maxrss: maximum resident set size
    • ru_ixrss: integral shared memory size
    • ru_idrss: integral unshared data size
    • ru_minflt: page reclaims
    • ru_majflt: page faults
    • ru_nsignals: signals received
    • ru_nvcsw: voluntary context switches
    • ru_nivcsw: involuntary context switches
    • ru_nswap: swaps
    • ru_utime.tv_usec: user time used (microseconds)
    • ru_utime.tv_sec: user time used (seconds)
    • ru_stime.tv_usec: system time used (microseconds)
    • ru_stime.tv_sec: system time used (seconds)
    •  

    To see how much CPU power the script has consumed, we need to look at the 'user time' and 'system time' values. The seconds and microseconds portions are provided separately by default. You can divide the microseconds value by 1 million, and add it to the seconds value, to get the total seconds as a decimal number.

    Let's see an example:

    01 // sleep for 3 seconds (non-busy)
    02 sleep(3);
    03  
    04 $data = getrusage();
    05 echo "User time: ".
    06 ($data['ru_utime.tv_sec'] +
    07 $data['ru_utime.tv_usec'] / 1000000);
    08 echo "System time: ".
    09 ($data['ru_stime.tv_sec'] +
    10 $data['ru_stime.tv_usec'] / 1000000);
    11 /* prints
    12 User time: 0.011552
    13 System time: 0
    14 */

    Even though the script took about 3 seconds to run, the CPU usage was very very low. Because during the sleep operation, the script actually does not consume CPU resources. There are many other tasks that may take real time, but may not use CPU time, like waiting for disk operations. So as you see, the CPU usage and the actual length of the runtime are not always the same.

    Here is another example:

    01 // loop 10 million times (busy)
    02 for($i=0;$i<10000000;$i++) {
    03  
    04 }
    05 $data = getrusage();
    06 echo "User time: ".
    07 ($data['ru_utime.tv_sec'] +
    08 $data['ru_utime.tv_usec'] / 1000000);
    09 echo "System time: ".
    10 ($data['ru_stime.tv_sec'] +
    11 $data['ru_stime.tv_usec'] / 1000000);
    12  
    13 /* prints
    14 User time: 1.424592
    15 System time: 0.004204
    16 */

    That took about 1.4 seconds of CPU time, almost all of which was user time, since there were no system calls. System Time is the amount of time the CPU spends performing system calls for the kernel on the program's behalf. Here is an example of that:

    01 $start = microtime(true);
    02 // keep calling microtime for about 3 seconds
    03 while(microtime(true) - $start < 3) {
    04  
    05 }
    06 $data = getrusage();
    07 echo "User time: ".
    08 ($data['ru_utime.tv_sec'] +
    09 $data['ru_utime.tv_usec'] / 1000000);
    10 echo "System time: ".
    11 ($data['ru_stime.tv_sec'] +
    12 $data['ru_stime.tv_usec'] / 1000000);
    13  
    14 /* prints
    15 User time: 1.088171
    16 System time: 1.675315
    17 */

    Now we have quite a bit of system time usage. This is because the script calls the microtime() function many times, which performs a request through the operating system to fetch the time.

    转自:http://www.ansoncheung.tk/articles/9-powerful-php-functions-you-should-know

  • 相关阅读:
    gridview 后台增加列
    SQL Server 触发器
    PIVOT 和 UNPIVOT 命令的SQL Server版本
    HtmlHelper.Raw,<%%>,<%:%>,<%=%>的区别及使用
    分布式搜索的面试题3
    分布式搜索的面试题2
    分布式搜索的面试题1
    消息队列的面试题7
    消息队列的面试题6
    消息队列的面试题5
  • 原文地址:https://www.cnblogs.com/chenqianpeng/p/2425733.html
Copyright © 2011-2022 走看看