你应该知道的9个强大的PHP函数

4
PHP JSON C/C++ Go 17111 次浏览
php-functions.jpg

包括:强大的文件查找功能,收集内存使用信息,生成唯一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:

// function with 2 optional arguments
function my_function($parameter1 = '', $parameter2 = '') {

     echo "parameter1: $parameter1\n";
     echo "parameter2: $parameter2\n";
}

foo('hello','anson cheung');
/* prints:
parameter1: hello
parameter2: anson cheung
*/
foo();
/* prints:
parameter1:
parameter2:
*/

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

// The argument list can be empty
function my_function() {

      // returns an array of all passed arguments
     $parameters = func_get_args();
     foreach ($parameters as $key => $value) {
       echo "parameter".($parameter+1).": $value\n";
     }

}
//Example 1
foo();
/* prints nothing */


//Example 2
foo('hello');
/* prints
parameter1: hello
*/

//Example 3
foo('hello', 'I am ', 'anson cheung');
/* prints
parameter1: hello
parameter2: I am 
parameter3: 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:

$files = glob('*.php');

print_r($files);

/* output looks like:
Array
(
    [0] => phptesting.php
    [1] => ptest.php
    [2] => post_output.php
    [3] => testing.php
)
*/

Example 2: Fetch multiple file types:

$files = glob('*.{php,txt}', GLOB_BRACE);

print_r($files);

/* output looks like:
Array
(
    [0] => phptesting.php
    [1] => ptest.php
    [2] => post_output.php
    [3] => testing.php
    [4] => log_file.txt
    [5] => test_2011.txt
)
*/

Example 3: Return files with a path:

$files = glob('../images/b*.jpg');

print_r($files);

/* output looks like:
Array
(
    [0] => ../images/baby.jpg
    [1] => ../images/babyboy.jpg
)
*/

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

$files = glob('../images/a*.jpg');


// applies the function to each array element
$files = array_map('realpath',$files);
print_r($files);

/* output looks like:
Array
(
    [0] => C:\xampp\www\images\angry.jpg
    [1] => C:\xampp\www\images\ajax.jpg
)
*/

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.

echo "Initial: ".memory_get_usage()." bytes \n";
/* prints
Initial: 361400 bytes
*/

// let's use up some memory
for ($i = 0; $i < 100000; $i++) {
$array []= md5($i);
}
// let's remove half of the array
for ($i = 0; $i < 100000; $i++) {
unset($array[$i]);
}

echo "Final: ".memory_get_usage()." bytes \n";
/* prints
Final: 885912 bytes
*/
echo "Peak: ".memory_get_peak_usage()." bytes \n";
/* prints
Peak: 13687072 bytes
*/

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__).

// 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\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.

// generate unique string
echo md5(time() . mt_rand(1,1000000));

In PHP, there is a function named as uniqid() that is meant to be used for this.
// generate unique string
echo uniqid();
/* prints
4bd67c947233e
*/

// generate another unique string
echo uniqid();
/* prints
4bd67c9472340
*/

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:

// 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
*/

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():

// 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
)
*/

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:

// 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
)
*/

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:

$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)."\n";
/* prints
Original size: 800
*/

echo "Compressed size: ". strlen($compressed)."\n";
/* prints
Compressed size: 418
*/
// getting it back
$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:

// 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.";

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:

$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.";
}

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

print_r(getrusage());
/* prints
Array
(
    [ru_oublock] => 0
    [ru_inblock] => 0
    [ru_msgsnd] => 2
    [ru_msgrcv] => 3
    [ru_maxrss] => 12692
    [ru_ixrss] => 764
    [ru_idrss] => 3864
    [ru_minflt] => 94
    [ru_majflt] => 0
    [ru_nsignals] => 1
    [ru_nvcsw] => 67
    [ru_nivcsw] => 4
    [ru_nswap] => 0
    [ru_utime.tv_usec] => 0
    [ru_utime.tv_sec] => 0
    [ru_stime.tv_usec] => 6269
    [ru_stime.tv_sec] => 0
)

*/

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:

// sleep for 3 seconds (non-busy)
sleep(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: 0.011552
System time: 0
*/

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:

// 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
*/

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:

$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
*/

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


请尽量让自己的答案能够对别人有帮助

7个答案

默认排序 按投票排序