8 Prerequisites for PHP feature Development _php Tutorial

Source: Internet
Author: User
Tags glob
Developers who have done PHP development 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 very practical, I hope that you PHP developers can master.

1, pass any number of function parameters we are 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: PHP code
    1. //two default parameter functions
    2. function foo ($arg 1 = ", $arg 2 =") {
    3. echo "Arg1: $arg 1 \ n ";
    4. echo "arg2: $arg 2\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 is an indeterminate parameter usage for PHP that uses [Url=http://us2.php.net/manual/en/function.func-get-args.php]func_get_args () [/url] Method:
    17. //Yes, parameter list is empty
    18. function foo () {
    19. //Get all array of incoming parameters
    20. $args = Func_get_args ();
    21. foreach ($args as $k = + $v) {
    22. echo "Arg". $k + 1). ": $v \ n";
    23. }
    24. }
    25. foo ();
    26. /* Nothing will 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, using Glob () Find files Most of the functions of PHP function name can literally understand its purpose, but when you see Glob (), you may not know what this is to do, in fact glob () and Scandir (), can be used to find files, see the following usage: PHP code
    1. Get all the files that are 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 multiple suffix names: PHP code
    1. Fetch PHP files 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 an 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. Get memory usage information PHP's memory recycling mechanism is very powerful, you can also use PHP script to get the current memory usage, call Memory_get_usage () function to get memory usage of the period, call Memory_get_peak_usage () function to get the peak memory usage. The reference code is as follows: PHP code
    1. echo "Initial:". Memory_get_usage (). "Bytes \ n";
    2. /* Output
    3. initial:361400 bytes
    4. */
    5. Using memory
    6. for ($i = 0; $i < 100000; $i + +) {
    7. $array []= MD5 ($i);
    8. }
    9. Delete half of the memory
    10. for ($i = 0; $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
    19. peak:13687072 bytes
    20. */
4, Get CPU usage information get memory usage, can also use PHP getrusage () to get CPU usage, this method is not available under 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] = 12692
    10. [Ru_ixrss] = 764
    11. [Ru_idrss] = 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] = 6269
    21. [Ru_stime.tv_sec] = 0
    22. )
    23. */
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: 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 Recycling
    • Ru_majflt: Page Failure
    • Ru_nsignals: Received Signal
    • RU_NVCSW: Active Context Switch
    • RU_NIVCSW: Passive Context Switch
    • Ru_nswap: Swap Area
    • 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. 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, we can take a look at the following example: PHP code
    1. Loop million times (busy)
    2. for ($i =0; $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. System time:0.004204
    14. */
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's 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. System time:1.675315
    15. */
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__), much like the 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. PHP code
    1. This was relative to the loaded script ' s path
    2. It may cause problems if running scripts from different directories
    3. Require_once (' config/database.php ');
    4. This is all relative to the this file ' s path
    5. No matter where it is included from
    6. Require_once (DirName (__file__). '/config/database.php ');
Here is the use of __line__ to output some debug information, which will help 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 unique numbers, but MD5 () has several drawbacks: 1, unordered, resulting 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: 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. */
The algorithm is generated according to the CPU time stamp, 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: PHP code
    1. Prefix
    2. echo uniqid (' Foo_ ');
    3. /* Output
    4. foo_4bd67d6cd8b8f
    5. */
    6. There's more entropy.
    7. Echo Uniqid (", true);
    8. /* Output
    9. 4bd67d6cd8b926.12135106
    10. */
    11. All have
    12. echo uniqid (' Bar_ ', true);
    13. /* Output
    14. bar_4bd67da367b650.43684647
    15. */
7, serialized PHP serialization function You may use more, also more common, when you need to save the data to the database or file is, you can use PHP serialize () and Unserialize () method 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, ' both '),
    6. ' Apple '
    7. );
    8. Serialization of
    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: "Both";} I:3;s:5: "Apple";}
    13. */
    14. Inverse order of the case
    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] =
    26. )
    27. [3] = Apple
    28. )
    29. */
How to serialize to JSON format, rest assured that PHP is ready for you, using PHP 5.2 or later users can use the Json_encode () and the Json_decode () function to implement the JSON format serialization, the code is as follows: PHP code
    1. A complex array
    2. $myvar = Array (
    3. ' Hello ',
    4. 42,
    5. Array (1, ' both '),
    6. ' Apple '
    7. );
    8. Convert to a string
    9. $string = Json_encode ($myvar);
    10. Echo $string;
    11. /* Prints
    12. ["Hello", 42,[1, "I"], "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] =
    26. )
    27. [3] = Apple
    28. )
    29. */
8, string compression when we talk about compression, we may think of file compression, in fact, the string can also be compressed. PHP provides the 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 pretium orci,
  6. Non ultricies elit lacus quis ante. Lorem ipsum dolor
  7. Sit amet, consectetur adipiscing elit. Aliquam
  8. Pretium ullamcorper 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. /* Output Original size
  21. Original size:800
  22. */
  23. echo "Compressed size:". Strlen ($compressed). " \ n ";
  24. /* Size after output is compressed
  25. Compressed size:418
  26. */
  27. Unzip
  28. $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?


Source: 8 PHP features to develop

http://www.bkjia.com/PHPjc/735057.html www.bkjia.com true http://www.bkjia.com/PHPjc/735057.html techarticle developers who have done PHP development 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 necessary ...

  • 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.