包括:强大的文件查找功能,收集内存使用信息,生成唯一ID,序列化,压缩字符串,CPU使用信息等。
Using 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:
02 |
function my_function( $parameter1 = '' , $parameter2 = '' ) { |
04 |
echo "parameter1: $parameter1\n" ; |
05 |
echo "parameter2: $parameter2\n" ; |
08 |
foo( 'hello' , 'anson cheung' ); |
Well, I am going to use func_get_args() to demonstrate you how we can build a function that accepts any number of arguments:
02 |
function my_function() { |
05 |
$parameters = func_get_args(); |
06 |
foreach ( $parameters as $key => $value ) { |
07 |
echo "parameter" .( $parameter +1). ": $value\n" ; |
23 |
foo( 'hello' , 'I am ' , 'anson cheung' ); |
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' ); |
Example 2: Fetch multiple file types:
01 |
$files = glob ( '*.{php,txt}' , GLOB_BRACE); |
Example 3: Return files with a path:
01 |
$files = glob ( '../images/b*.jpg' ); |
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' ); |
05 |
$files = array_map ( 'realpath' , $files ); |
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" ; |
07 |
for ( $i = 0; $i < 100000; $i ++) { |
11 |
for ( $i = 0; $i < 100000; $i ++) { |
15 |
echo "Final: " .memory_get_usage(). " bytes \n" ; |
19 |
echo "Peak: " .memory_get_peak_usage(). " bytes \n" ; |
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__).
03 |
my_debug( "some debug message" , __LINE__ ); |
10 |
my_debug( "another debug message" , __LINE__ ); |
14 |
function my_debug( $msg , $line ) { |
15 |
echo "Line $line: $msg\n" ; |
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.
02 |
echo md5(time() . mt_rand(1,1000000)); |
04 |
In PHP, there is a function named as uniqid() that is meant to be used for this. |
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:
13 |
echo uniqid( 'bar_' ,true); |
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():
10 |
$string = serialize( $myvar ); |
17 |
$newvar = unserialize( $string ); |
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:
10 |
$string = json_encode( $myvar ); |
17 |
$newvar = json_decode( $string ); |
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:
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. "; |
19 |
$compressed = gzcompress( $string ); |
20 |
echo "Original size: " . strlen ( $string ). "\n" ; |
25 |
echo "Compressed size: " . strlen ( $compressed ). "\n" ; |
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:
2 |
$start_time = microtime(true); |
7 |
echo "execution took: " . |
8 |
(microtime(true) - $start_time ). |
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); |
03 |
register_shutdown_function( 'my_shutdown' ); |
07 |
function my_shutdown() { |
09 |
echo "execution took: " . |
10 |
(microtime(true) - $start_time ). |
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
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:
06 |
( $data [ 'ru_utime.tv_sec' ] + |
07 |
$data [ 'ru_utime.tv_usec' ] / 1000000); |
09 |
( $data [ 'ru_stime.tv_sec' ] + |
10 |
$data [ 'ru_stime.tv_usec' ] / 1000000); |
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:
02 |
for ( $i =0; $i <10000000; $i ++) { |
07 |
( $data [ 'ru_utime.tv_sec' ] + |
08 |
$data [ 'ru_utime.tv_usec' ] / 1000000); |
10 |
( $data [ 'ru_stime.tv_sec' ] + |
11 |
$data [ 'ru_stime.tv_usec' ] / 1000000); |
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); |
03 |
while (microtime(true) - $start < 3) { |
08 |
( $data [ 'ru_utime.tv_sec' ] + |
09 |
$data [ 'ru_utime.tv_usec' ] / 1000000); |
11 |
( $data [ 'ru_stime.tv_sec' ] + |
12 |
$data [ 'ru_stime.tv_usec' ] / 1000000); |
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