9 required Practical PHP functions and functions

Source: Internet
Author: User
Tags glob
9 required Practical PHP functions and functions

This article introduces toceansoft.


Even if you have been using PHP for many years, you may find some functions and functions that you have never understood. Some of them are very useful, but they are not fully utilized. Not everyone will read the manual and function reference page by page from start to end!

1, Any number of parameters function

You may already know that PHP allows defining functions with optional parameters. However, there are methods that fully allow any number of function parameters. The following is an example of an optional parameter:

// Function with 2 optional arguments
Function foo ($ arg1 = ", $ arg2 = "){

Echo "arg1: $ arg1n ";
Echo "arg2: $ arg2n ";

}

Foo ('hello', 'World ');
/* Prints:
Arg1: hello
Arg2: world
*/

Foo ();
/* Prints:
Arg1:
Arg2:
*/

Now let's see how to create a function that can accept any number of parameters. This time, you need to use the func_get_args () function:

// Yes, the argument list can be empty
Function foo (){

// Returns an array of all passed arguments
$ Args = func_get_args ();

Foreach ($ args as $ k =>v v ){
Echo "arg". ($ k + 1). ": $ vn ";
}

}

Foo ();
/* Prints nothing */

Foo ('Hello ');
/* Prints
Arg1: hello
*/

Foo ('hello', 'World', 'Again ');
/* Prints
Arg1: hello
Arg2: world
Arg3: again
*/

2Use Glob () to find files

Many PHP functions have long descriptive names. However, it may be difficult to say what the glob () function can do unless you have used it many times and are familiar with it. You can think of it as a version that is more powerful than the scandir () function. you can search for files in a certain mode.

// Get all php files
$ Files = glob ('*. php ');

Print_r ($ files );
/* Output looks like:
Array
(
[0] => phptest. php
[1] => pi. php
[2] => post_output.php
[3] => test. php
)
*/

You can obtain multiple files like this:

// Get all php files AND txt files
$ Files = glob ('*. {php, txt}', GLOB_BRACE );

Print_r ($ files );
/* Output looks like:
Array
(
[0] => phptest. php
[1] => pi. php
[2] => post_output.php
[3] => test. php
[4] => log.txt
[5] => test.txt
)
*/

Note that these files can actually return a path, depending on the query conditions:

$ Files = glob ('../images/a *. jpg ');

Print_r ($ files );
/* Output looks like:
Array
(
[0] => ../images/apple.jpg
[1] => ../images/art.jpg
)
*/

If you want to obtain the complete path of each file, you can call the realpath () function:

$ Files = glob ('../images/a *. jpg ');

// Applies the function to each array element
$ Files = array_map ('realpath', $ files );

Print_r ($ files );
/* Output looks like:
Array
(
[0] => C: wampwwwimagesapple.jpg
[1] => C: wampwwwimagesart.jpg
)
*/

3Memory usage information

By detecting the memory usage of the script, the code is optimized. PHP provides a garbage collector and a very complex memory manager. The amount of memory used for script execution is increased or decreased. To get the current memory usage, we can use the memory_get_usage () function. To obtain the maximum memory usage at any time point, you can use the memory_limit () function.

Echo "Initial:". memory_get_usage (). "bytes n ";
/* Prints
Initialize: 361400 bytes
*/

// Let's use up some memory
For ($ I = 0; I I <100000; $ I ++ ){
$ Array [] = md5 ($ I );
}

// Let's remove half of the array
For ($ I = 0; I I <100000; $ I ++ ){
Unset ($ array [$ I]);
}

Echo "Final:". memory_get_usage (). "bytes n ";
/* Prints
Final: 885912 bytes
*/

Echo "Peak:". memory_get_peak_usage (). "bytes n ";
/* Prints
Peak: 13687072 bytes
*/

4CPU usage information

Therefore, we need to use the getrusage () function. Remember that this function is not applicable to Windows.

Print_r (getrusage ());
/* Prints
Array
(
[Ru_oublock] => 0
[Ru_inblock] => 0
[Ru_msgsnd] => 2
[Ru_msgrcv] => 3
[Ru_maxrss] = & gt; 12692
[Ru_ixrss] = & gt; 764
[Ru_idrss] = & gt; 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] = & gt; 6269
[Ru_stime. TV _sec] => 0
)

*/

This may seem a bit mysterious, unless you have the system administrator privilege. The following is a detailed description of each value (you do not need to remember this ):

Ru_oublock: block output operations
Ru_inblock: block input operations
Ru_msgsnd: messages sent
Ru_msgrcv: messages received
Ru_maxrss: maximum resident set size
Ru_ixrss: integral shared memory size
Ru_idrss: integral unshared data size
Ru_minflt: page reclaims
Ru_majflt: page faults
Ru_nsignals: signals passed Ed
Ru_nvcsw: voluntary context switches
Ru_nivcsw: involuntary context switches
Ru_nswap: swaps
Ru_utime. TV _usec: user time used (microseconds)
Ru_utime. TV _sec: user time used (seconds)
Ru_stime. TV _usec: system time used (microseconds)
Ru_stime. TV _sec: system time used (seconds)

To know how much CPU power the script consumes, we need to look at the values of the 'user time' and 'system time' parameters. Seconds and microseconds are provided separately by default. You can divide by 1 million microseconds and add the parameter value of seconds to get the total number of seconds in decimal format. Let's take an example:

// 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 );

/* Prints
User time: 0.011552
System time: 0
*/

The CPU usage is very low even though it takes about three seconds to run the script. This script does not actually consume CPU resources during sleep. There are many other tasks that may take some time, but do not occupy CPU time, such as waiting for disk operations. So as you can see, the actual length of CPU usage and running time is not always the same. The following is an example:

// Loop 10 million times (busy)
For ($ I = 0; I 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 );

/* Prints
User time: 1.424592
Time: 0.004204
*/

This takes about 1.4 seconds of CPU time, but almost all of them are user time, because there is no system call. System time refers to the CPU overhead spent on executing the program's system call. The following is an example:

$ Start = microtime (true );
// Keep calling microtime for about 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 );

/* Prints
User time: 1.088171
Time: 1.675315
*/

Now we have a considerable amount of system time. This is because the script calls the microtime () function multiple times and sends a request to the operating system to obtain the required time. You may also notice that the running time is less than 3 seconds. This is because there may be other processes on the server at the same time, and the script does not have 100% CPU usage throughout the three seconds.

5, Magic constant

PHP provides the ability to obtain the current LINE number (_ LINE _), FILE path (_ FILE _), and directory path (_ DIR __), FUNCTION name (_ FUNCTION _), CLASS name (_ CLASS _), METHOD name (_ METHOD _), and NAMESPACE (_ NAMESPACE __) and other useful magic constants. I will not describe them one by one in this article, but I will tell you some examples. When other script files are included, use the _ FILE _ constant (or use the new _ DIR _ constant in PHP5.3 ):

// This is relative to the loaded script's path
// It may cause problems when running scripts from different directories
Require_once ('config/database. php ');

// This is always relative to this file's path
// No matter where it was encoded ded from
Require_once (dirname (_ FILE _). '/config/database. php ');

Use _ LINE _ to make debugging easier. You can trace the specific row number.

// Some code
//...
My_debug ("some debug message" ,__ LINE __);
/* Prints
Line 4: some debug message
*/

// Some more code
//...
My_debug ("another debug message", _ LINE __);
/* Prints
Line 11: another debug message
*/

Function my_debug ($ msg, $ line ){
Echo "Line $ line: $ msgn ";
}

6Generate a unique identifier

In some scenarios, you may need to generate a unique string. I have seen many people use the md5 () function, even though it does not completely mean this purpose:

// Generate unique string
Echo md5 (time (). mt_rand (1,000000 ));

There is actually a PHP function named uniqid () that ismeant to be used for this.

// Generate unique string
Echo uniqid ();
/* Prints
4bd67c947233e
*/

// Generate another unique string
Echo uniqid ();
/* Prints
4bd67c9472340
*/

Although the string is unique, the first few characters are similar, because the generated string is related to the server time. But in fact, there is also a friendly aspect, because each newly generated ID will be sorted in alphabetical order, so the sorting becomes very simple. To reduce the probability of repetition, you can pass a prefix or a second parameter to increase the entropy:

// With prefix
Echo uniqid ('foo _');
/* Prints
Foo_4bd67d6cd8b8f
*/

// With more entropy
Echo uniqid (", true );
/* Prints
4bd67d6cd8b926. 12135106
*/

// Both
Echo uniqid ('Bar _ ', true );
/* Prints
Bar_4bd67da% B %.4%4647
*/

This function will generate strings shorter than md5 (), saving some space.

7Serialization

Have you ever encountered the need to store a complex variable in a database or text file? You may not be able to figure out a good way to format a string and convert it to an array or object. PHP has prepared this function for you. There are two popular methods to serialize variables. The following is an example using the serialize () and unserialize () functions:

// A complex array
$ Myvar = array (
'Hello ',
42,
Array (1, 'two '),
'Apple'
);

// Convert to a string
$ String = serialize ($ myvar );

Echo $ string;
/* Prints
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 ";}
*/

// You can reproduce the original variable
$ Newvar = unserialize ($ string );

Print_r ($ newvar );
/* Prints
Array
(
[0] => hello
[1] => 42
[2] => Array
(
[0] => 1
[1] => two
)

[3] => apple
)
*/

This is the native PHP Serialization method. However, as JSON has gained popularity in recent years, PHP5.2 has added support for JSON format. Now you can use the json_encode () 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 );
/* Prints
Array
(
[0] => hello
[1] => 42
[2] => Array
(
[0] => 1
[1] => two
)

[3] => apple
)
*/

This will be more effective, especially compatible with many other languages such as JavaScript. However, for complex objects, some information may be lost.

8, Compression string

When talking about compression, we usually think of file compression, such as ZIP compression. String compression is also possible in PHP, but does not involve any compressed files. In the following example, we will use 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 presponorci,
Non ultricies elit lacus quis ante. Lorem ipsum dolor
Sit amet, consectetur adipiscing elit. Aliquam
Prepolicullamcorper 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 ";
/* Prints
Original size: 800
*/

Echo "Compressed size:". strlen ($ compressed). "n ";
/* Prints
Compressed size: 418
*/

// Getting it back
$ Original = gzuncompress ($ compressed );

The compression ratio of this operation can reach about 50%. In addition, the gzencode () and gzdecode () functions can achieve similar results by using different compression algorithms.

9, Registration stop function

There is a function called register_shutdown_function () that allows you to execute some specified code before a script is executed. Suppose you need to capture some baseline statistics before the script execution ends, such as the running duration:

// Capture the start time
$ Start_time = microtime (true );

// Do some stuff
//...

// Display how long the script took
Echo "execution took:".
(Microtime (true)-$ start_time ).
"Seconds .";

This seems insignificant. you only need to add the relevant code at the end of the script. However, if you call the exit () function, the code cannot run. In addition, if there is a fatal error or the script is accidentally terminated by the user, it may not run again. When you use the register_shutdown_function () function, the code continues to be executed, regardless of whether or not the script stops running:

$ 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 .";
}

I like my articles. please follow my toceansoft


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.