Php development tips 1: Below are nine useful functions in PHP. do you know you have used them? 1. any number of function parameters you may know that PHP allows you to define a function with default parameters. But you may not know that PHP also allows you to define a function that is completely arbitrary. The following is an example showing you the default...
1. any number of parameters of the function
You may know that PHP allows you to define a default parameter function. But you may not know that PHP also allows you to define a function with all arbitrary parameters.
The following example shows the default parameter functions:
Function foo ($ arg1 = '', $ arg2 ='') {echo "arg1: $ arg1 \ n"; echo "arg2: $ arg2 \ n ";} foo ('helloarg2, 'World');/* output: arg1: helloarg2: world */foo ();/* output: arg1: arg2 :*/
Now let's take a look at a function with an indefinite parameter. is it used? Func_get_args () method:
// Yes, the parameter list is empty function foo () {// get all input parameter arrays $ args = func_get_args (); foreach ($ args as $ k => $ v) {echo "arg ". ($ k + 1 ). ": $ v \ n" ;}} foo ();/* no output */foo ('Hello');/* output arg1: hello */foo ('hello', 'World', 'Again ');/* output arg1: helloarg2: worldarg3: again */
2. use Glob () to find files
Many PHP functions have a long self-explanatory function name? During glob (), you may not know what this function is for, unless you are familiar with it.
Do you think this function is good? Like scandir (), scandir can be used to find files.
// Obtain all files suffixed with PHP $ files = glob ('*. php '); print_r ($ files);/* output: Array ([0] => phptest. php [1] => pi. php [2] => post_output.php [3] => test. php) */You can also find a variety of extensions // Retrieve the php file and TXT file $ files = glob ('*. {php, txt} ', GLOB_BRACE); print_r ($ files);/* output: Array ([0] => phptest. php [1] => pi. php [2] => post_output.php [3] => test. php [4] => log.txt [5] => test.txt )*/
// You can add the path $ files = glob ('.. /images/*. jpg '); print_r ($ files);/* output: Array ([0] => .. /images/apple.jpg [1] => .. /images/art.jpg) * // If you want to obtain an absolute path, can you call it? Realpath () function: $ files = glob ('.. /images/*. jpg '); // applies the function to each array element $ files = array_map ('realpath', $ files); print_r ($ files);/* output looks like: array ([0] => C: \ wamp \ www \ images \ apple.jpg [1] => C: \ wamp \ www \ images \ art.jpg )*/
3. memory usage information
Observe that the memory usage of your program allows you to better optimize your code.
PHP has a garbage collection mechanism and a complicated memory management mechanism. You can know the memory usage of your script. Do you want to know the current memory usage? Memory_get_usage () function. if you want to know the peak memory usage, you can call the memory_get_peak_usage () function.
Echo "Initial :". memory_get_usage (). "bytes \ n";/* output Initial: 361400 bytes * // memory usage for ($ I = 0; $ I <100000; $ I ++) {$ array [] = md5 ($ I) ;}// delete half of the memory for ($ 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";/* output Peak: 13687072 bytes */
4. CPU usage information
Use? The getrusage () function allows you to know the CPU usage. Note that this function is not available in Windows.
Print_r (getrusage ()); /* output 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) */this structure seems obscure unless you know the CPU. The following are some explanations: ru_oublock: block output operation ru_inblock: block input operation ru_msgsnd: sent messageru_msgrcv: received messageru_maxrss: maximum resident set large and small ru_ixrss: all shared memory size ru_idrss: all non-shared memory size ru_minflt: page recycling ru_majflt: Page failure ru_nsignals: Received signal ru_nvcsw: active context switching ru_nivcsw: passive context switching ru_nswap: Swap Zone duration: User state Time (microseconds) ru_utime. TV _sec: User State time (seconds) ru_stime. TV _usec: System Kernel time (microseconds) ru_stime. TV _sec: System Kernel time? (Seconds) to see how much CPU your script consumes, we need to look at the values of "user-mode time" and "system kernel time. Second and microsecond are provided separately. you can divide the microsecond value by 1 million and add it to the second value to obtain the number of seconds with a decimal part. // 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);/* output User time: 0.011552 System time: 0 */sleep does not occupy the System time. let's take a look at the following example: // loop 10 million times (busy) for ($ I = 0; $ I <10000000; $ I ++) {}$ data = getrusage (); echo "User time: ". ($ d Ata ['Ru _ utime. TV _sec '] + $ data ['Ru _ utime. TV _usec ']/1000000); echo "System time :". ($ data ['Ru _ stime. TV _sec '] + $ data ['Ru _ stime. TV _usec ']/1000000);/* output User time: 1.424592 System time: 0.004204 */this takes about 14 seconds of CPU time, almost all of which are User time, because there is no system call. The system time is the time when the CPU spends executing kernel commands on system calls. 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.088171 System time: 1.675315 */We can see that the above example consumes more CPU.
5. system constants
PHP provides very useful system constants for you to get the current row number (_ LINE _), FILE (_ FILE _), Directory (_ DIR __), FUNCTION name (_ FUNCTION _), CLASS name (_ CLASS _), METHOD name (_ METHOD _), and NAMESPACE (_ NAMESPACE __), similar to C language.
We can think that these things are mainly used for debugging, but they are not necessarily the same. for example, we can use them when include other files? _ FILE _ (of course, you can also use _ DIR _ after PHP 5.3). The following is an example.
/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 encoded Ded fromrequire_once (dirname (_ FILE __). '/config/database. php '); // The following uses _ LINE _ to output some debug information, which helps you debug the program: // some code //... my_debug ("some debug message", _ LINE _);/* output Line 4: some debug message * // some more code //... my_debug ("another debug message", _ LINE _);/* output Line 11: another debug message */function my_debug ($ msg, $ line) {echo "Line $ line: $ msg \ n ";}
6. generate a unique ID
Many users use md5 () to generate a unique ID, as shown below:
// Generate unique stringecho md5 (time (). mt_rand (); in fact, there is a name in PHP? The uniqid () function is specifically used to do this: // generate unique stringecho uniqid ();/* output 4bd67c947233e * // generate another unique stringecho uniqid (); /* output 4bd67c9472340 */You may notice that the first few digits of the generated ID are the same, because the generator depends on the system time, which is actually a very good function, because you can easily sort your IDs. This MD5 cannot be achieved. You can also add a prefix to avoid duplicate names: // prefix echo uniqid ('foo _ ');/* output foo_4bd67d6cd8b8f * // more entropy echo uniqid ('', true);/* output 4bd67d6cd8b926. 12135106 * // all have echo uniqid ('Bar _ ', true);/* output bar_4bd67da1_b0000.43664647 */. the generated ID is shorter than the one generated by MD5, this will save you a lot of space.
7. serialization
Will you store a complicated data structure in a database or file? You do not need to write your own algorithms. PHP has already been ready for you. it provides two functions :? Serialize () and unserialize ():
// A complex array $ myvar = array ('hello', 42, array (1, 'two'), 'apple '); // serialize $ string = serialize ($ myvar); echo $ string;/* output 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";} * // reverse sample $ newvar = unserialize ($ string); print_r ($ newvar ); /* output Array ([0] => hello [1] => 42 [2] => Array ([0] => 1 [1] => two) [3] => apple) */This is the native function of PHP. However, JSON is becoming more and more popular today, so after PHP5.2, PHP began to support JSON. you can use json_encod. E () 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) */It looks more compact and compatible with Javas Other languages. However, some very complex data structures may cause data loss.
8. string compression
When we talk about compression, we may think of file compression. In fact, strings can also be compressed. PHP provides? 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 presponorci, non ultricies elit lacus quis ante. lorem ipsum dolorsit amet, consectetur adipiscing elit. aliquamprepolicullamcorper urna quis iaculis. etiam ac massased turpis tempor luctus. curabitur sed nibh eu elitmol Lis 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";/* Original output size Original size: 800 */echo "Compressed size :". strlen ($ compressed ). "\ n";/* output Compressed size: 418 * // Extract $ original = gzuncompress ($ compressed); almost 50% compression ratio. At the same time, you can also use? Gzencode () and gzdecode () functions to compress, instead of using different compression algorithms.
9. Register the stop function
Is there a function called? Register_shutdown_function () allows you to run the code before the entire script is stopped. Let's take a look at the following example:
// Capture the start time $ start_time = microtime (true); // do some stuff //... // display how long the script tookecho "execution took :". (microtime (true)-$ start_time ). "seconds. "; the above example is only used to calculate the running time of a function. Then, if you call it in the middle of the function? Exit () function, then your final code will not be run. In addition, if the script is terminated in the browser (the user presses the stop button), it cannot be run. When register_shutdown_function () is used, your program will be run even after the script is stopped: $ 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. ";}