Nine required Practical PHP functions and functions

Source: Internet
Author: User
Tags glob
Nine essential practical PHP functions and functions [go] even if you have been using PHP for many years, you may find some functions and functions that you have never understood. Some of them are very useful, but they are not fully utilized. Not everyone will read the manual and function reference page by page from start to end! 1. functions with any number of parameters you may already know. PHP allows defining functions with optional parameters. However, there are also nine Practical PHP functions and functions that must be fully known. [go to]

Even if you have been using PHP for many years, you may find some functions and functions that you have never understood. Some of them are very useful, but they are not fully utilized. Not everyone will read the manual and function reference page by page from start to end!

1. functions with any number of parameters

You may already know that PHP allows defining functions with optional parameters. However, there are methods that fully allow any number of function parameters. The following is an example of an optional parameter:

// function with 2 optional argumentsfunction foo($arg1 = '', $arg2 = '') { echo "arg1: $arg1n"; echo "arg2: $arg2n";}foo('hello','world');/* prints:arg1: helloarg2: world*/foo();/* prints:arg1:arg2:*/

Now let's see how to create a function that can accept any number of parameters. This time, you need to use the func_get_args () function:

// yes, the argument list can be emptyfunction foo() { // returns an array of all passed arguments $args = func_get_args(); foreach ($args as $k => $v) {  echo "arg".($k+1).": $vn"; }}foo();/* prints nothing */foo('hello');/* printsarg1: hello*/foo('hello', 'world', 'again');/* printsarg1: helloarg2: worldarg3: again*/

2. use Glob () to find files

Many PHP functions have long descriptive names. However, it may be difficult to say what the glob () function can do unless you have used it many times and are familiar with it. You can think of it as a version that is more powerful than the scandir () function. you can search for files in a certain mode.

// get all php files$files = glob('*.php');print_r($files);/* output looks like:Array(    [0] => phptest.php    [1] => pi.php    [2] => post_output.php    [3] => test.php)*/

You can obtain multiple files like this:

// get all php files AND txt files$files = glob('*.{php,txt}', GLOB_BRACE);print_r($files);/* output looks like:Array(    [0] => phptest.php    [1] => pi.php    [2] => post_output.php    [3] => test.php    [4] => log.txt    [5] => test.txt)*/

Note that these files can actually return a path, depending on the query conditions:

$files = glob('../images/a*.jpg');print_r($files);/* output looks like:Array(    [0] => ../images/apple.jpg    [1] => ../images/art.jpg)*/

If you want to obtain the complete path of each file, you can call the realpath () function:

$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:wampwwwimagesapple.jpg    [1] => C:wampwwwimagesart.jpg)*/

3. memory usage information

By detecting the memory usage of the script, the code is optimized. PHP provides a garbage collector and a very complex memory manager. The amount of memory used for script execution is increased or decreased. To get the current memory usage, we can use the memory_get_usage () function. To obtain the maximum memory usage at any time point, you can use the memory_limit () function.

echo "Initial: ".memory_get_usage()." bytes n";/* printsInitial: 361400 bytes*/// let's use up some memoryfor ($i = 0; $i < 100000; $i++) { $array []= md5($i);}// let's remove half of the arrayfor ($i = 0; $i < 100000; $i++) { unset($array[$i]);}echo "Final: ".memory_get_usage()." bytes n";/* printsFinal: 885912 bytes*/echo "Peak: ".memory_get_peak_usage()." bytes n";/* printsPeak: 13687072 bytes*/

4. CPU usage information

Therefore, we need to use the getrusage () function. Remember that this function is not applicable to Windows.

print_r(getrusage());/* printsArray(    [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)*/

This may seem a bit mysterious, unless you have the system administrator privilege. The following is a detailed description of each value (you do not need to remember this ):

ru_oublock: block output operationsru_inblock: block input operationsru_msgsnd: messages sentru_msgrcv: messages receivedru_maxrss: maximum resident set sizeru_ixrss: integral shared memory sizeru_idrss: integral unshared data sizeru_minflt: page reclaimsru_majflt: page faultsru_nsignals: signals receivedru_nvcsw: voluntary context switchesru_nivcsw: involuntary context switchesru_nswap: swapsru_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 know how much CPU power the script consumes, we need to look at the values of the 'user time' and 'system time' parameters. Seconds and microseconds are provided separately by default. You can divide by 1 million microseconds and add the parameter value of seconds to get the total number of seconds in decimal format. Let's take 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);/* printsUser time: 0.011552System time: 0*/

The CPU usage is very low even though it takes about three seconds to run the script. This script does not actually consume CPU resources during sleep. There are many other tasks that may take some time, but do not occupy CPU time, such as waiting for disk operations. So as you can see, the actual length of CPU usage and running time is not always the same. The following is an 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);/* printsUser time: 1.424592System time: 0.004204*/

This takes about 1.4 seconds of CPU time, but almost all of them are user time, because there is no system call. System time refers to the CPU overhead spent on executing the program's system call. The following is an example:

$start = microtime(true);// keep calling microtime for about 3 secondswhile(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);/* printsUser time: 1.088171System time: 1.675315*/

Now we have a considerable amount of system time. This is because the script calls the microtime () function multiple times and sends a request to the operating system to obtain the required time. You may also notice that the running time is less than 3 seconds. This is because there may be other processes on the server at the same time, and the script does not have 100% CPU usage throughout the three seconds.

5. magic constants

PHP provides the ability to obtain the current LINE number (_ LINE _), FILE path (_ FILE _), and directory path (_ DIR __), FUNCTION name (_ FUNCTION _), CLASS name (_ CLASS _), METHOD name (_ METHOD _), and NAMESPACE (_ NAMESPACE __) and other useful magic constants. I will not describe them one by one in this article, but I will tell you some examples. When other script files are included, use the _ FILE _ constant (or use the new _ DIR _ constant in PHP5.3 ):

// this is relative to the loaded script's path// it may cause problems when running scripts from different directoriesrequire_once('config/database.php');// this is always relative to this file's path// no matter where it was included fromrequire_once(dirname(__FILE__) . '/config/database.php');

Use _ LINE _ to make debugging easier. You can trace the specific row number.

// some code// ...my_debug("some debug message", __LINE__);/* printsLine 4: some debug message*/// some more code// ...my_debug("another debug message", __LINE__);/* printsLine 11: another debug message*/function my_debug($msg, $line) { echo "Line $line: $msgn";}

6. generate a unique identifier

In some scenarios, you may need to generate a unique string. I have seen many people use the md5 () function, even though it does not completely mean this purpose:

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

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

// generate unique stringecho uniqid();/* prints4bd67c947233e*/// generate another unique stringecho uniqid();/* prints4bd67c9472340*/

Although the string is unique, the first few characters are similar, because the generated string is related to the server time. But in fact, there is also a friendly aspect, because each newly generated ID will be sorted in alphabetical order, so the sorting becomes very simple. To reduce the probability of repetition, you can pass a prefix or a second parameter to increase the entropy:

// with prefixecho uniqid('foo_');/* printsfoo_4bd67d6cd8b8f*/// with more entropyecho uniqid('',true);/* prints4bd67d6cd8b926.12135106*/// bothecho uniqid('bar_',true);/* printsbar_4bd67da367b650.43684647*/

This function will generate strings shorter than md5 (), saving some space.

7. serialization

Have you ever encountered the need to store a complex variable in a database or text file? You may not be able to figure out a good way to format a string and convert it to an array or object. PHP has prepared this function for you. There are two popular methods to serialize variables. The following is an example using the serialize () and unserialize () functions:

// a complex array$myvar = array( 'hello', 42, array(1,'two'), 'apple');// convert to a string$string = serialize($myvar);echo $string;/* printsa: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);/* printsArray(    [0] => hello    [1] => 42    [2] => Array        (            [0] => 1            [1] => two        )    [3] => apple)*/

This is the native PHP Serialization method. However, as JSON has gained popularity in recent years, PHP5.2 has added support for JSON format. Now you can use the json_encode () and json_decode () functions:

// 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);/* printsArray(    [0] => hello    [1] => 42    [2] => Array        (            [0] => 1            [1] => two        )    [3] => apple)*/

This will be more effective, especially compatible with many other languages such as JavaScript. However, for complex objects, some information may be lost.

8. compress strings

When talking about compression, we usually think of file compression, such as ZIP compression. String compression is also possible in PHP, but does not involve any compressed files. In the following example, we will use the gzcompress () and gzuncompress () functions:

$string ="Lorem ipsum dolor sit amet, consecteturadipiscing elit. Nunc ut elit id mi ultriciesadipiscing. Nulla facilisi. Praesent pulvinar,sapien vel feugiat vestibulum, nulla dui pretium orci,non ultricies elit lacus quis ante. Lorem ipsum dolorsit amet, consectetur adipiscing elit. Aliquampretium ullamcorper urna quis iaculis. Etiam ac massased turpis tempor luctus. Curabitur sed nibh eu elitmollis congue. Praesent ipsum diam, consectetur vitaeornare a, aliquam a nunc. In id magna pellentesquetellus posuere adipiscing. Sed non mi metus, at laciniaaugue. Sed magna nisi, ornare in mollis in, mollissed nunc. Etiam at justo in leo congue mollis.Nullam in neque eget metus hendrerit scelerisqueeu non enim. Ut malesuada lacus eu nulla bibendumid euismod urna sodales. ";$compressed = gzcompress($string);echo "Original size: ". strlen($string)."n";/* printsOriginal size: 800*/echo "Compressed size: ". strlen($compressed)."n";/* printsCompressed size: 418*/// getting it back$original = gzuncompress($compressed);

The compression ratio of this operation can reach about 50%. In addition, the gzencode () and gzdecode () functions can achieve similar results by using different compression algorithms.

9. disable registration

There is a function called register_shutdown_function () that allows you to execute some specified code before a script is executed. Suppose you need to capture some basic quasi-statistical information before the script execution ends, such as the running duration:

// capture the start time$start_time = microtime(true);// do some stuff// ...// display how long the script tookecho "execution took: ".  (microtime(true) - $start_time).  " seconds.";

This seems insignificant. you only need to add the relevant code at the end of the script. However, if you call the exit () function, the code cannot run. In addition, if there is a fatal error or the script is accidentally terminated by the user, it may not run again. When you use the register_shutdown_function () function, the code continues to be executed, regardless of whether or not the script stops 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.";}

Original English version: 9 Useful PHP Functions and Features You Need to Know | Nettuts
9 Practical PHP functions and functions that must be known | Mango

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.