8 Prerequisites for PHP feature development, PHP required
PHP developers should be aware that PHP has a lot of built-in features, mastered them, can help you in the development of PHP more handy, this article will share 8 development of the necessary PHP features, all are very practical, I hope that you PHP developers can master.
1, pass any number of function parameters
We're in. NET or Java programming, the number of general function parameters is fixed, but PHP allows you to use any number of parameters. The following example shows you the default parameters for PHP functions:
The following example is an indeterminate parameter usage of PHP that uses the Func_get_args () method:
Yes, the formal parameter list is empty function foo () {//Gets an array of all 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
The function names of most PHP functions can literally understand their purpose, but when you see Glob (), you may not know what this is for, in fact Glob () and Scandir () can be used to find files, see the following usage:
You can also add a path:
$files = Glob ('.. /images/a*.jpg '); Print_r ($files); /* Output: Array ([0] = =. /IMAGES/APPLE.JPG[1] =. /images/art.jpg) */
If you want an absolute path, you can call the Realpath () function:
3. Get Memory usage information
PHP's memory recovery mechanism is very powerful, you can also use PHP script to get the current memory usage, call the Memory_get_usage () function to get memory usage in the period, call the Memory_get_peak_usage () function to get the peak memory usage. The reference code is as follows:
echo "Initial:". Memory_get_usage (). "Bytes \ n"; /* Output initial:361400 bytes*///Use memory for ($i = 0; $i < 100000; $i + +) {$array []= MD5 ($i);}//delete half of 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. Get CPU usage information
Get memory usage, or use PHP's Getrusage () to get CPU usage, which is not available under 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 looks very obscure, unless you know the CPU well. Here are some explanations:
ru_oublock: Block output Operation
Ru_inblock: block input action
RU_MSGSND: Message sent
RU_MSGRCV: Message received
Ru_ Maxrss: Maximum resident set size
Ru_ixrss: Total shared memory size
Ru_idrss: Total non-shared memory size
Ru_minflt: page Reclaim
Ru_majflt: Page invalidation
Ru_nsignals: Signal received
RU_NVCSW: Active context Toggle
RU_NIVCSW: Passive context switch
Ru_nswap: Swap
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 the system time, we can take a look at the following example://Loop million times (busy) for ($i =0; $i <10000 $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 on 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); /* Printsuser Time:1.088171system time:1.675315*/
We can see that the above example consumes more CPU.
5. Get 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 directories R Equire_once (' config/database.php '); This is all relative to the this file's path//no matter where it was included from Require_once (DirName (__file__). '/config/database.php ');
Here is the use of __line__ to output some debug information, which will help you debug your program:
6. Generate a unique ID
Many friends use MD5 () to generate unique numbers, but MD5 () has several drawbacks: 1, unordered, which results in degraded sorting performance in the database. 2, too long, need more storage space. In fact, PHP comes with a function to generate a unique ID, this function is Uniqid (). Here's how to use:
Generate Unique string echo uniqid (); /* Output 4bd67c947233e*///Generate another unique string echo uniqid (); /* Output 4bd67c9472340*/
The algorithm is generated according to the CPU timestamp, so in a similar time period, the ID of the first few are the same, it is convenient to sort the ID, if you want to better avoid repetition, you can prefix the ID, such as:
Prefix echo uniqid (' Foo_ '); /* Output foo_4bd67d6cd8b8f*///have more entropy echo uniqid (", true); /* Output 4bd67d6cd8b926.12135106*///both have echo uniqid (' Bar_ ', true); /* Output bar_4bd67da367b650.43684647*/
7. Serialization
PHP serialization features are probably more common, and when you need to store the data in a database or file, you can use PHP's serialize () and Unserialize () methods to achieve serialization and deserialization, the code is as follows:
How to serialize to JSON format, rest assured, PHP is ready for you, using PHP 5.2 or later users can use the Json_encode () and Json_decode () function to implement the JSON format serialization, the code is as follows:
A complex Array$myvar = array (' Hello ',, Array (1, ' both '), ' 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); Print_r ($newvar); /* Printsarray ([0] = = hello[1] = 42[2] = = Array ([0] = 1[1] [+] [3] = apple) */
8, string compression
When we talk about compression, we may think of file compression, in fact, strings can be compressed. PHP provides the 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 "; /* Output Original size original size:800*/echo "Compressed size:". Strlen ($compressed). " \ n "; /* Output Compressed size compressed size:418*///Uncompressed $orIginal = gzuncompress ($compressed);
There are almost 50% compression ratios. You can also use the Gzencode () and Gzdecode () functions to compress without using a different compression algorithm.
The above is the 8 development of the necessary PHP features, is not all very practical?
http://www.bkjia.com/PHPjc/1058153.html www.bkjia.com true http://www.bkjia.com/PHPjc/1058153.html techarticle 8 PHP features must be developed, the PHP developer must be aware that PHP has a lot of built-in features, mastered them, can help you in the development of PHP more handy, ...