1. Any number of parameters of the function
You may know that PHP allows you to define a function of a default parameter. But you may not know that PHP also allows you to define a function of an entirely arbitrary parameter
Here is an example of a function that shows you the default parameters:
Copy Code code as follows:
Two functions for default parameters
function foo ($arg 1 = ', $arg 2 = ') {
echo "Arg1: $arg 1\n";
echo "ARG2: $arg 2\n";
}
Foo (' Hello ', ' world ');
/* Output:
Arg1:hello
Arg2:world
*/
Foo ();
/* Output:
Arg1:
ARG2:
*/
Now let's take a look at a function with an indefinite parameter, which uses the? Func_get_args () Method:
Yes, the formal parameter list is empty
function foo () {
Gets the array of all incoming arguments
$args = Func_get_args ();
foreach ($args as $k => $v) {
echo "Arg". ($k + 1). ": $v \ n";
}
}
Foo ();
* * Nothing will be output/
Foo (' Hello ');
/* Output
Arg1:hello
*/
Foo (' Hello ', ' world ', ' again ');
/* Output
Arg1:hello
Arg2:world
Arg3:again
*/
2. Use Glob () to find files
Many PHP functions have a long, self explanatory function name, but when you see Glob (), you may not know what the function is for, unless you are already familiar with it.
You can think of this function as good? Scandir (), it can be used to find files.
Copy Code code as follows:
Get all the suffixes for php files
$files = Glob (' *.php ');
Print_r ($files);
/* Output:
Array
(
[0] => phptest.php
[1] => pi.php
[2] => post_output.php
[3] => test.php
)
*/
You can also find multiple suffix names
Take PHP files and txt files
$files = Glob (' *.{ Php,txt} ', glob_brace);
Print_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 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:
$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:\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 is a garbage collection mechanism, and has a very complex memory management mechanism. 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 value of memory use, you can call the Memory_get_peak_usage () function.
Copy Code code as follows:
echo "Initial:". Memory_get_usage (). "Bytes \ n";
/* Output
initial:361400 bytes
*/
Using memory
for ($i = 0; $i < 100000; $i + +) {
$array []= MD5 ($i);
}
Remove half of the memory
for ($i = 0; $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";
/* 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.
Copy Code code as follows:
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 is 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: All non-shared memory sizes
Ru_minflt: Page Recycling
Ru_majflt: Page Expiration
Ru_nsignals: The signal received
RU_NVCSW: Active Context switching
RU_NIVCSW: Passive Context switching
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 value of "User state Time" and "System kernel Time". The second and microsecond portions are provided separately, and you can divide the microsecond value by 1 million and add it to the value of the second, and you can get the number of seconds that have a decimal part.
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.011552
System time:0
*/
Sleep does not occupy the 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.424592
System time:0.004204
*/
This takes about 14 seconds of CPU time, almost all of which are user time, because there is no system call.
System time is the time that the CPU spends executing kernel instructions on the system call. Here is an example:
Copy Code code as follows:
$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
System 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 name Space (__namespace__), much like C language.
We can assume that these things are mainly for debugging, and when not necessarily, for example, we can use the __file__ when including other files (of course, you can also use __dir__ after PHP 5.3), here is an example.
Copy Code code as follows:
This is relative to the loaded script ' s path
It may cause problems if running scripts from different directories
Require_once (' config/database.php ');
This is always relative to this file ' s path
No matter where it is included from
Require_once (DirName (__file__). '/config/database.php ');
The following is the use of __line__ to output some of the 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 string
echo MD5 (Time (). Mt_rand (1,1000000));
In fact, there is a function in PHP called UNIQID () that is specifically used to do this:
Generate unique string
Echo Uniqid ();
/* Output
4bd67c947233e
*/
Generate another unique string
Echo Uniqid ();
/* Output
4bd67c9472340
*/
You may notice that the first few generated IDs are the same, because the generator relies on the time of the system, which is actually a very good feature because you are easily sorted for your IDs. This MD5 is not to be done.
You can also prefix to avoid duplicate names:
Prefix
echo uniqid (' Foo_ ');
/* Output
foo_4bd67d6cd8b8f
*/
There's more entropy.
Echo uniqid (', true ');
/* Output
4bd67d6cd8b926.12135106
*/
All have
echo uniqid (' Bar_ ', true);
/* Output
bar_4bd67da367b650.43684647
*/
Also, the generated IDs will be shorter than those generated by MD5, which can save you a lot of space.
Username: Password: New user registration PHP100 Three non-Treaty contributors website Home | PHP Industry | Web Development Information | Video Tutorials | PHP Open Source | Related Downloads | PHP Job Opportunities | Project Supply and Demand | Resource Sharing | PHP100 Chinese Forum Apache | Mysql | PHP | JavaScript | Ajax | XML | Div&css | Linux | Database technology
Information class Home > Web Development materials > PHP > PHP application > Nine PHP useful features nine PHP very useful features
Time: 2011-07-08 00:18 from: coolshell.cn Author: coolshell.cn Click: 5,403 times "font size: Big small" 1. Any number of arguments to a function you might know that PHP allows you to define a function of a default parameter. But you may not know that PHP also allows you to define a function that is completely arbitrary. The following is an example of a function that shows you the default parameter://Two functions of the default parameter foo ($arg 1 = ', $arg 2 = ') {echo arg1: $ar
7. Serialization of
Do you store a more complex data structure in a database or file? You don't have to write your own algorithm. PHP has already been done for you, and it provides two functions:? Serialize () and Unserialize ():
Copy Code code as follows:
A complex array of
$myvar = Array (
' Hello ',
42,
Array (1, ' two '),
' Apple '
);
Serialization of
$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: "Two";} I:3;s:5: "Apple";}
*/
Inverse order of the case
$newvar = Unserialize ($string);
Print_r ($newvar);
/* Output
Array
(
[0] => Hello
[1] => 42
[2] => Array
(
[0] => 1
[1] => two
)
[3] => Apple
)
*/
This is the native function of PHP, but today the JSON is getting popular, so after PHP5.2, PHP starts to support JSON, 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 looks a little more compact, and is also compatible with JavaScript and other languages. However, for some very complex data structures, data loss may result.
8. String compression
When we talk about compression, we might think of file compression, but strings can also be compressed. PHP provides the gzcompress () and Gzuncompress () functions:
Copy Code code as follows:
$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,
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, 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 size after compression
Compressed size:418
*/
Decompression
$original = gzuncompress ($compressed);
There are almost 50% compression ratios. At the same time, you can use the Gzencode () and Gzdecode () functions to compress, using only a different compression algorithm.
9. Register Stop function
There is a function called a register_shutdown_function () that lets you run the code before the entire script stops. Let's look at one of the following examples:
Copy Code code as follows:
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.";
The above example is simply used to calculate when a function is running. Then, if you call the exit () function in the middle of the function, 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 is 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.";
}