PHP Development Tips One

Source: Internet
Author: User
Tags glob

The following is a useful feature in PHP nine, do not know if you have used it? 1. Any number of arguments to the function you probably know that PHP allows you to define a default parameter for a function. But you may not know that PHP also allows you to define a function of a completely arbitrary parameter below is an example showing you the default ...

1. Any number of arguments to the function

You probably know that PHP allows you to define a default parameter for a function. But you may not know that PHP also allows you to define a function of a completely arbitrary parameter

The following is an example of a function that shows you the default parameters:

function foo ($arg 1 = ", $arg 2 = ') {echo" arg1: $arg 1\n "; echo" arg2: $arg 2\n ";} Foo (' Hello ', ' world ');/* Output: Arg1:helloarg2:world*/foo ();/* Output: arg1:arg2:*/

now let's take a look at the function of an indefinite parameter, which is used? Func_get_args () method:

Yes, the formal parameter list is empty function foo () {//Gets all the array of incoming parameters $args = Func_get_args (); foreach ($args as $k = + $v) {echo "arg". $k + 1). ": $v \ n";}} Foo ();/* Nothing will 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, but when you see the Glob (), you probably don't know what the function is for, unless you're familiar with it.

You can think of this function as good? Scandir (), which can be used to find files.

Get all the suffixes for php files $files = glob (' *.php ');p rint_r ($files);/* Output: Array (    [0] = phptest.php    [1] = pi.php    [2] = post_output.php    [3] = = test.php) * * You can also find multiple suffix names//fetch PHP files and txt files $files = glob (' *.{ Php,txt} ', Glob_brace);p Rint_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 also add the path: $files = Glob ('.. /images/a*.jpg ');p rint_r ($files);/* Output: Array (    [0] = =. /images/apple.jpg    [1] = =. /images/art.jpg) *///If you want an absolute path, you can call the? Realpath () function: $files = Glob ('. /images/a*.jpg '),//Applies the function to each array element$files = Array_map (' Realpath ', $files);p Rint_r ($files);/* Output looks like:array (    [0] = C:\wamp\www\images\apple.jpg    [1] = C:\wamp\www\images\art.jpg) */


3. Memory usage Information

Observing the memory usage of your program allows you to better optimize your code.

PHP has a garbage collection mechanism, and a complex set of memory management mechanisms. You can know the memory used by your script. To know the current memory usage, you can use the? Memory_get_usage () function, and if you want to know the peak use memory, you can call the Memory_get_peak_usage () function.

echo "Initial:". Memory_get_usage (). "Bytes \ n";/* output initial:361400 bytes*///use memory for ($i = 0; $i < 100000; $i + +) {$ar Ray []= 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 peak:13687072 bytes*/


4.CPU usage Information

Use the Getrusage () function to let you know the CPU usage. Note that this feature is not available under Windows.

Print_r (Getrusage ());/* Output Array ([Ru_oublock] + 0 [Ru_inblock] = 0 [RU_MSGSND] = 2 [RU_MSGRCV] =&G T  3 [Ru_maxrss] = 12692 [Ru_ixrss] = 764 [Ru_idrss] = 3864 [Ru_minflt] = 94 [Ru_majflt] = 0 [Ru_nsignals] + 1 [RU_NVCSW] = [RU_NIVCSW] 4 [Ru_nswap] = 0 [ru_utime.tv_usec] =&gt ; 0 [Ru_utime.tv_sec] = 0 [Ru_stime.tv_usec] = 6269 [ru_stime.tv_sec] + 0) */This structure looks very obscure, unless you know the CPU well. Here are some explanations: ru_oublock: Block output operation Ru_inblock: Block input operation Ru_msgsnd: Sent MESSAGERU_MSGRCV: Received Messageru_maxrss: Maximum resident set size Ru_ixrss: Total Shared memory size Ru_idrss: All non-shared memory size Ru_minflt: Page Recycle Ru_majflt: Page invalidation ru_nsignals: Received signal RU_NVCSW: Active context Switch RU_NIVCSW: Passive context Switch Ru_nswap : Swap zone ru_utime.tv_usec: 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 "user-state time" and "system kernel Time" values. Seconds and microseconds are provided separately, and you can divide the microsecond value by 1 million and add it to the second value to get the number of seconds that have fractional parts. 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.011552system Time:0*/sleep is not taking up system time , we can look at one of the following examples://loop 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);/* Output User Time:1.424592system time:0.004204*/ This took about 14 seconds of CPU time, almost all of it was user time, because there was no system call. The system time is the time that the CPU spends executing kernel instructions on the system call. Here is an example: $start = Microtime (TRUE);//Keep calling Microtime for about 3 Secondswhile (Microtime (True)-$start < 3) {} $da Ta = 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*/ We can see that the above example consumes more CPU.


5. System Constants

PHP provides very useful system constants that allow you to get the current line number (__line__), file (__file__), directory (__dir__), function name (__function__), class name (__class__), method name (__method__) and namespace (__namespace__), very much like C language.

We can assume that these things are mainly used for debugging, and when not necessarily, for example, can we use other files when we include them? __file__ (of course, you can also use __dir__ after PHP 5.3), here's an example.

/This was relative to the loaded script ' s path//it could cause problems when running scripts from different directoriesrequ Ire_once (' config/database.php ');//This is the relative to this file ' s path//no matter where it was included Fromrequi Re_once (DirName (__file__). '/config/database.php ');//The following is the use of __line__ to output some debug information, which will help 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

A lot of people use MD5 () to generate a unique ID, as follows:

Generate unique Stringecho MD5 (time (). Mt_rand (1,1000000)); in fact, PHP has a function called uniqid () is specifically used to do this://Generate Unique Stringecho uniqid ();/* Output 4bd67c947233e*///generate another unique Stringecho uniqid ();/* Output 4bd67c9472340*/ Maybe you'll notice that the first few of the generated IDs are the same, because the generator relies on the system time, which is actually a very nice feature, because you are very easy to sort these IDs for you. This MD5 is not to be done. You can also add prefixes to avoid duplicate names://prefix echo uniqid (' Foo_ ');/* Output foo_4bd67d6cd8b8f*///have more entropy echo uniqid (", true);/* The output 4bd67d6cd8b926.12135106*///has echo uniqid (' Bar_ ', true);/* Output bar_4bd67da367b650.43684647*/and the generated ID will be shorter than the MD5 generated, This will save you a lot of space.

7. Serialization

Do you have a more complex data structure stored in a database or file? You don't need to write your own algorithm. PHP is already ready for you, and it provides two functions:? Serialize () and Unserialize ():

A complex array of $myvar = Array (' Hello ', 42,array (1, ' one '), ' Apple ');//Serialization $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: "Both";} I:3;s:5: "Apple";}         *///$newvar = unserialize ($string);p rint_r ($newvar);/* Output Array ([0] = hello [1] = [2] = = Array ([0] = 1 [1] = two) [3] = apple) */This is the native function of PHP, but today JSON is becoming more and more popular, so in PHP5. After 2, PHP began to support JSON, you can use Json_encode () and Json_decode () function//a complex Array$myvar = array (' Hello ', 42,array (1, ' "), ' Apple ');//Convert to a string$string = Json_encode ($myvar); echo $string;/* prints["Hello", 42,[1, "I", "Apple"]*///    You can reproduce the original Variable$newvar = Json_decode ($string);p rint_r ($newvar);/* Printsarray ([0] = = Hello [1] = [2] = = Array ([0] = 1 [1] = +) [3] = apple) */ This looks more compact and is also compatible with JavaScript and other languages. But for some very complex data structures, data loss can result

8. String compression

When we talk about compression, we may think of file compression, in fact, strings can also be compressed. PHP provides 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 ";/* Output Original size original Size:800*/echo" Compressed size: ". Strlen ($compressed). " \ n "/* Output Compressed size compressed size:418*///extract $original = gzuncompress ($compressed); almost 50% compression ratios. Also, you can use the Gzencode () and Gzdecode () functions to compress without using a different compression algorithm.

9. Registration Stop function

There is a function called register_shutdown_function (), which allows you to run the code before the entire script is stopped. Let's look at one of the following examples:

Capture the start Time$start_time = Microtime (TRUE);//Do some stuff//...//display how long the script Tookecho "exec Ution took: ". (Microtime (True)-$start _time). " seconds. "; The above example is only used to calculate when a function is running. Then, if you call the exit () function in the middle of the function, then your final code will not be run to. Also, if the script terminates in the browser (the user presses the Stop button), it cannot be run. And when we use Register_shutdown_function (), 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.";}


PHP Development Tips One

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.