8 required PHP function development _ PHP Tutorial

Source: Internet
Author: User
Tags glob
Develop eight essential PHP functions. Programmers who have developed PHP should be clear that PHP has many built-in functions and can master them to help you better develop PHP, this article will share eight essential PHP Development programmers who have done PHP Development. it should be clear that PHP has many built-in functions that can help you better develop PHP, this article will share eight essential PHP functions, all of which are very practical and I hope all PHP developers can master them.

1. transfer any number of function parameters. in. NET or JAVA programming, the number of function parameters is fixed, but PHP allows you to use any number of parameters. The following example shows the default parameter of the PHP function: Php code.
  1. // Functions with two default parameters
  2. Function foo ($ arg1 = ", $ arg2 = "){
  3. Echo "arg1: $ arg1 \ n ";
  4. Echo "arg2: $ arg2 \ n ";
  5. }
  6. Foo ('hello', 'World ');
  7. /* Output:
  8. Arg1: hello
  9. Arg2: world
  10. */
  11. Foo ();
  12. /* Output:
  13. Arg1:
  14. Arg2:
  15. */
  16. The following example shows the variable parameter usage of PHP. the [url = http://us2.php.net/manual/en/function.func-get-args.php?func_get_args () [/url] method is used:
  17. // Yes, the parameter list is empty
  18. Function foo (){
  19. // Obtain the array of all input parameters
  20. $ Args = func_get_args ();
  21. Foreach ($ args as $ k =>v v ){
  22. Echo "arg". ($ k + 1). ": $ v \ n ";
  23. }
  24. }
  25. Foo ();
  26. /* Nothing will be output */
  27. Foo ('Hello ');
  28. /* Output
  29. Arg1: hello
  30. */
  31. Foo ('hello', 'World', 'Again ');
  32. /* Output
  33. Arg1: hello
  34. Arg2: world
  35. Arg3: again
  36. */
2. you can use glob () to find the function names of most PHP functions in a file. However, when you see glob, you may not know what this is for. In fact, glob () is the same as scandir () and can be used to find files. please refer to the following usage: Php code
  1. // Obtain all files suffixed with PHP
  2. $ Files = glob ('*. php ');
  3. Print_r ($ files );
  4. /* Output:
  5. Array
  6. (
  7. [0] => phptest. php
  8. [1] => pi. php
  9. [2] => post_output.php
  10. [3] => test. php
  11. )
  12. */
You can also find a variety of extensions: Php code
  1. // Retrieve the PHP and TXT files
  2. $ Files = glob ('*. {php, txt}', GLOB_BRACE );
  3. Print_r ($ files );
  4. /* Output:
  5. Array
  6. (
  7. [0] => phptest. php
  8. [1] => pi. php
  9. [2] => post_output.php
  10. [3] => test. php
  11. [4] => log.txt
  12. [5] => test.txt
  13. )
  14. */
You can also add the path: Php code
  1. $ Files = glob ('../images/a *. jpg ');
  2. Print_r ($ files );
  3. /* Output:
  4. Array
  5. (
  6. [0] => ../images/apple.jpg
  7. [1] => ../images/art.jpg
  8. )
  9. */
If you want to obtain the absolute path, you can call the realpath () function: Php code.
  1. $ Files = glob ('../images/a *. jpg ');
  2. // Applies the function to each array element
  3. $ Files = array_map ('realpath', $ files );
  4. Print_r ($ files );
  5. /* Output looks like:
  6. Array
  7. (
  8. [0] => C: \ wamp \ www \ images \ apple.jpg
  9. [1] => C: \ wamp \ www \ images \ art.jpg
  10. )
  11. */
3. obtain memory usage information the PHP memory recovery mechanism is very powerful. you can also use the PHP script to obtain the current memory usage and call the memory_get_usage () function to obtain the current memory usage, call the memory_get_peak_usage () function to obtain the peak memory usage. The reference code is as follows: Php code
  1. Echo "Initial:". memory_get_usage (). "bytes \ n ";
  2. /* Output
  3. Initialize: 361400 bytes
  4. */
  5. // Memory usage
  6. For ($ I = 0; I I <100000; $ I ++ ){
  7. $ Array [] = md5 ($ I );
  8. }
  9. // Delete half of the memory
  10. For ($ I = 0; I I <100000; $ I ++ ){
  11. Unset ($ array [$ I]);
  12. }
  13. Echo "Final:". memory_get_usage (). "bytes \ n ";
  14. /* Prints
  15. Final: 885912 bytes
  16. */
  17. Echo "Peak:". memory_get_peak_usage (). "bytes \ n ";
  18. /* Output peak value
  19. Peak: 13687072 bytes
  20. */
4. obtain the CPU usage information to obtain the memory usage, or use getrusage () of PHP to obtain the CPU usage. this method is unavailable in windows. Php code
  1. Print_r (getrusage ());
  2. /* Output
  3. Array
  4. (
  5. [Ru_oublock] => 0
  6. [Ru_inblock] => 0
  7. [Ru_msgsnd] => 2
  8. [Ru_msgrcv] => 3
  9. [Ru_maxrss] = & gt; 12692
  10. [Ru_ixrss] = & gt; 764
  11. [Ru_idrss] = & gt; 3864
  12. [Ru_minflt] => 94
  13. [Ru_majflt] => 0
  14. [Ru_nsignals] => 1
  15. [Ru_nvcsw] => 67
  16. [Ru_nivcsw] => 4
  17. [Ru_nswap] => 0
  18. [Ru_utime. TV _usec] => 0
  19. [Ru_utime. TV _sec] => 0
  20. [Ru_stime. TV _usec] = & gt; 6269
  21. [Ru_stime. TV _sec] => 0
  22. )
  23. */
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 message
  • Ru_msgrcv: Received message
  • Ru_maxrss: the largest and smallest resident set
  • Ru_ixrss: all shared memory size
  • Ru_idrss: all non-shared memory sizes
  • Ru_minflt: page recycling
  • Ru_majflt: The page is invalid.
  • Ru_nsignals: Received signal
  • Ru_nvcsw: active context switching
  • Ru_nivcsw: passive context switching
  • 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 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. Php code
  1. // Sleep for 3 seconds (non-busy)
  2. Sleep (3 );
  3. $ Data = getrusage ();
  4. Echo "User time:".
  5. ($ Data ['Ru _ utime. TV _sec '] +
  6. $ Data ['Ru _ utime. TV _usec']/1000000 );
  7. Echo "System time:".
  8. ($ Data ['Ru _ stime. TV _sec '] +
  9. $ Data ['Ru _ stime. TV _usec ']/1000000 );
  10. /* Output
  11. User time: 0.011552
  12. System time: 0
  13. */
Sleep does not occupy the system time. let's take a look at the following example: Php code
  1. // Loop 10 million times (busy)
  2. For ($ I = 0; I I <10000000; $ I ++ ){
  3. }
  4. $ Data = getrusage ();
  5. Echo "User time:".
  6. ($ Data ['Ru _ utime. TV _sec '] +
  7. $ Data ['Ru _ utime. TV _usec']/1000000 );
  8. Echo "System time:".
  9. ($ Data ['Ru _ stime. TV _sec '] +
  10. $ Data ['Ru _ stime. TV _usec ']/1000000 );
  11. /* Output
  12. User time: 1.424592
  13. Time: 0.004204
  14. */
This took about 14 seconds of CPU time, almost all of which were user time, because there was no system call. The system time is the time when the CPU spends executing kernel commands on system calls. The following is an example: Php code
  1. $ Start = microtime (true );
  2. // Keep calling microtime for about 3 seconds
  3. While (microtime (true)-$ start <3 ){
  4. }
  5. $ Data = getrusage ();
  6. Echo "User time:".
  7. ($ Data ['Ru _ utime. TV _sec '] +
  8. $ Data ['Ru _ utime. TV _usec']/1000000 );
  9. Echo "System time:".
  10. ($ Data ['Ru _ stime. TV _sec '] +
  11. $ Data ['Ru _ stime. TV _usec ']/1000000 );
  12. /* Prints
  13. User time: 1.088171
  14. Time: 1.675315
  15. */
We can see that the above example consumes more CPU. 5. retrieving system constants PHP provides very useful system constants that allow you to obtain the current row number (_ LINE _), FILE (_ FILE __), directory (_ DIR _), FUNCTION name (_ FUNCTION _), CLASS name (_ CLASS _), METHOD name (_ METHOD __) it is similar to the NAMESPACE (_ NAMESPACE. 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. Php code
  1. // This is relative to the loaded script's path
  2. // It may cause problems when running scripts from different directories
  3. Require_once ('config/database. php ');
  4. // This is always relative to this file's path
  5. // No matter where it was encoded ded from
  6. Require_once (dirname (_ FILE _). '/config/database. php ');
The following uses _ LINE _ to output some debug information, which helps you debug the program: Php code
  1. // Some code
  2. //...
  3. My_debug ("some debug message", _ LINE __);
  4. /* Output
  5. Line 4: some debug message
  6. */
  7. // Some more code
  8. //...
  9. My_debug ("another debug message", _ LINE __);
  10. /* Output
  11. Line 11: another debug message
  12. */
  13. Function my_debug ($ msg, $ line ){
  14. Echo "Line $ line: $ msg \ n ";
  15. }
6. generate a unique id many friends use md5 () to generate a unique id. However, md5 () has several disadvantages: 1. unordered, leading to a decline in database sorting performance. 2. it is too long and requires more storage space. In fact, PHP comes with a function to generate a unique id. This function is uniqid (). Below is the usage: Php code
  1. // Generate unique string
  2. Echo uniqid ();
  3. /* Output
  4. 4bd67c947233e
  5. */
  6. // Generate another unique string
  7. Echo uniqid ();
  8. /* Output
  9. 4bd67c9472340
  10. */
This algorithm is generated based on the CPU time stamp. Therefore, the first few digits of the id are the same in a similar period of time, which facilitates id sorting. if you want to avoid duplication, you can add a prefix before the id, for example, Php code.
  1. // Prefix
  2. Echo uniqid ('foo _');
  3. /* Output
  4. Foo_4bd67d6cd8b8f
  5. */
  6. // More entropy
  7. Echo uniqid (", true );
  8. /* Output
  9. 4bd67d6cd8b926. 12135106
  10. */
  11. // All have
  12. Echo uniqid ('Bar _ ', true );
  13. /* Output
  14. Bar_4bd67da% B %.4%4647
  15. */
7. serialization PHP Serialization functions may be widely used and common. when you need to store data in a database or file, you can use serialize () in PHP () and unserialize () methods to achieve serialization and deserialization. the code is as follows: Php code
  1. // A complex array
  2. $ Myvar = array (
  3. 'Hello ',
  4. 42,
  5. Array (1, 'two '),
  6. 'Apple'
  7. );
  8. // Serialization
  9. $ String = serialize ($ myvar );
  10. Echo $ string;
  11. /* Output
  12. 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 ";}
  13. */
  14. // Reverse sample
  15. $ Newvar = unserialize ($ string );
  16. Print_r ($ newvar );
  17. /* Output
  18. Array
  19. (
  20. [0] => hello
  21. [1] => 42
  22. [2] => Array
  23. (
  24. [0] => 1
  25. [1] => two
  26. )
  27. [3] => apple
  28. )
  29. */
How to serialize data to json format? rest assured that php is ready for you. users who use php 5.2 or later can use the json_encode () and json_decode () functions to serialize data in json format, the code is as follows: Php code
  1. // A complex array
  2. $ Myvar = array (
  3. 'Hello ',
  4. 42,
  5. Array (1, 'two '),
  6. 'Apple'
  7. );
  8. // Convert to a string
  9. $ String = json_encode ($ myvar );
  10. Echo $ string;
  11. /* Prints
  12. ["Hello", 42, [1, "two"], "apple"]
  13. */
  14. // You can reproduce the original variable
  15. $ Newvar = json_decode ($ string );
  16. Print_r ($ newvar );
  17. /* Prints
  18. Array
  19. (
  20. [0] => hello
  21. [1] => 42
  22. [2] => Array
  23. (
  24. [0] => 1
  25. [1] => two
  26. )
  27. [3] => apple
  28. )
  29. */
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: Php code
  1. $ String =
  2. "Lorem ipsum dolor sit amet, consectetur
  3. Adipiscing elit. Nunc ut elit id mi ultricies
  4. Adipiscing. Nulla facilisi. Praesent pulvinar,
  5. Sapien vel feugiat vestibulum, nulla dui presponorci,
  6. Non ultricies elit lacus quis ante. Lorem ipsum dolor
  7. Sit amet, consectetur adipiscing elit. Aliquam
  8. Prepolicullamcorper urna quis iaculis. Etiam ac massa
  9. Sed turpis tempor luctus. Curabitur sed nibh eu elit
  10. Mollis congue. Praesent ipsum diam, consectetur vitae
  11. Ornare a, aliquam a nunc. In id magna pellentesque
  12. Tellus posuere adipiscing. Sed non mi metus, at lacinia
  13. Augue. Sed magna nisi, ornare in mollis in, mollis
  14. Sed nunc. Etiam at justo in leo congue mollis.
  15. Nullam in neque eget metus hendrerit scelerisque
  16. Eu non enim. Ut malesuada lacus eu nulla bibendum
  17. Id euismod urna sodales. ";
  18. $ Compressed = gzcompress ($ string );
  19. Echo "Original size:". strlen ($ string). "\ n ";
  20. /* Original output size
  21. Original size: 800
  22. */
  23. Echo "Compressed size:". strlen ($ compressed). "\ n ";
  24. /* Output compressed size
  25. Compressed size: 418
  26. */
  27. // Extract
  28. $ Original = gzuncompress ($ compressed );
The compression ratio is almost 50%. At the same time, you can use the gzencode () and gzdecode () functions to compress, instead of using different compression algorithms. The above eight PHP functions are essential for development. are they all very practical?


Source: eight essential PHP functions

...

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.