Even if you're using PHP for years, you'll stumble across functions and functions that you never knew about. Some of them are very useful, but not fully utilized. Not everyone will read the manual and function references from beginning to end.
1, any number of parameters of the function
As you may already know, PHP allows you to define functions for optional parameters. But there is also a way to fully allow any number of function parameters. The following are examples of optional parameters:
function with 2 optional arguments
function foo ($arg 1 = ', $arg 2 = ') {
echo "arg1: $arg 1\n";
echo "ARG2: $arg 2\n";
}
Foo (' Hello ', ' world ');
/* Prints:
arg1:hello
arg2:world
* *
foo ();
/* Prints:
arg1:
arg2:
* *
Now let's look at how to create a function that accepts any number of arguments. This time you need to use the Func_get_args () function:
Yes, the argument list can be empty
function foo () {
//Returns a array of all passed arguments
$args = Func_get_args ();
foreach ($args as $k => $v) {
echo "arg". ( $k + 1). ": $v \ n";
}
}
Foo ();
/* Prints Nothing *
/foo (' Hello ');
/*
Prints
arg1:hello
/foo (' Hello ', ' world ', ' again ');
/* Prints
arg1:hello
arg2:world
arg3:again
* *
2. Use 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 become familiar with it. You can think of it as a more powerful version than the Scandir () function, and you can search for files in a pattern.
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 get 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 are actually able to return a path, depending on the query criteria:
$files = Glob ('.. /images/a*.jpg ');
Print_r ($files);
/* Output looks like:
Array
(
[0] =>. /images/apple.jpg
[1] =>. /images/art.jpg
)
* * *
If you want to get the full path to 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:\wamp\www\images\apple.jpg
[1] => C:\wamp\www\images\ Art.jpg
)
* * *
3, Memory usage information
It is advantageous to code optimization by detecting memory usage of scripts. PHP provides a garbage collector and a very complex memory manager. The amount of memory that the script uses when it executes, with a rise or fall. In order to get the current memory usage, we can use the Memory_get_usage () function. You can use the Memory_limit () function if you need to obtain the highest amount of memory usage at any point in time.
echo "Initial:". Memory_get_usage (). "Bytes \ n";
* Prints
initial:361400 bytes
*//Let's use up
some memory for
($i = 0; $i < 100000; $i + +) {
$a Rray []= MD5 ($i);
}
Let's remove half of the array 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";
/* Prints
peak:13687072 bytes
* *
4. CPU usage Information
To do this, we use the Getrusage () function. Keep in mind that this function does not apply to Windows platforms.
Print_r (Getrusage ());
/* Prints
Array
(
[Ru_oublock] => 0
[Ru_inblock] => 0
[ru_msgsnd] => 2
[RU_MSGRCV] = > 3
[ru_maxrss] => 12692
[Ru_ixrss] => 764
[Ru_idrss] => 3864
[Ru_minflt] =>
Ru_majflt] => 0
[ru_nsignals] => 1
[RU_NVCSW] =>
[RU_NIVCSW] => 4
[Ru_nswap] => 0< C16/>[RU_UTIME.TV_USEC] => 0
[ru_utime.tv_sec] => 0
[ru_stime.tv_usec] => 6269
[ru_stime.tv_ SEC] => 0
)
* *
This may seem a bit cryptic, unless you already have system administrator privileges. Here's a specific description of each value (you don't need to remember these):
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 received<
C9/>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 ' two parameters. The seconds and microseconds sections are provided separately by default. You can divide by 1 million microseconds and add a second parameter value to get the total number of seconds in a decimal. Let's take a look at 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
* *
Although the script runs for about 3 seconds, CPU usage is very, very low. Because the script does not actually consume CPU resources during sleep running. There are many other tasks that may take a while, but do not occupy CPU time such as waiting for disk operations. So as you can see, the actual length of CPU usage and elapsed time is not always the same. Here is an example:
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);
/* Prints
User time:1.424592
System time:0.004204
* *
This took about 1.4 seconds of CPU time, but almost all of it was user time because there was no system call. System time is the CPU overhead spent executing a system call to the program. Here is an example:
$start = Microtime (true);
Keep calling microtime for about 3 seconds while
Microtime (true)-$start < 3) {
}
$data = Getrusage (); C4/>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
* *
Now we have quite a lot of system time to occupy. This is because the script calls the Microtime () function multiple times, and the function needs to make a request to the operating system to get the time it takes. You may also notice that the running time adds up to less than 3 seconds. This is because it is possible to have other processes on the server at the same time, and the script does not have 100% of the entire 3-second duration of CPU use.
5. Magic Constants
PHP provides access to the current line number (__line__), file path (__file__), directory path (__dir__), function name (__function__), class name (__class__), method name (__method__), and namespace (__ NAMESPACE__) and other useful magic constants. Not to mention it in this article, but I'll show you some use cases. Use the __FILE__ constant when you include other script files (or use the PHP5.3 new __dir__ constants):
This is relative to the loaded script's path
//It may cause problems when running scripts from different Directori Es
require_once (' config/database.php ');
This is always relative to this file's path
//No matter where it was included from
require_once (dirname __) . '/config/database.php ');
Using __line__ makes debugging easier. You can track the specific line 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: $msg \ n ";
}
6. Generate a unique identifier
In some scenarios, you might want to generate a unique string. I've seen a lot of people using the MD5 () function, even if it doesn't exactly mean that purpose:
Generate unique String
echo MD5 (Time (). Mt_rand (1,1000000));
There is actually a PHP function named Uniqid (), which is meant to, used for this.
Generate unique String
echo uniqid ();
/* Prints
4bd67c947233e
*//
generate another unique string
echo uniqid ();
/* Prints
4bd67c9472340
* *
You may notice that although the string is unique, the first few characters are similar because the generated string is related to the server time. But there is also a friendly aspect to it, because each newly generated ID is sorted alphabetically, so that the sorting becomes 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_4bd67da367b650.43684647
* *
This function will produce a shorter string than MD5 (), saving some space.
7. Serialization of
Have you ever encountered a situation where you 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 strings and transform an array or object, and PHP is ready for you. There are two popular methods for serializing variables. Here is an example of using the Serialize () and Unserialize () functions:
A complex array
$myvar = array (
' hello ', +,
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] =>
[2] => array
(
[0] => 1
[1 ] => two
)
[3] => Apple
)
* *
This is a native PHP serialization method. However, thanks to JSON's popularity in recent years, support for JSON format has been added to PHP5.2. Now you can use the Json_encode () and Json_decode () functions:
A complex array
$myvar = array (
' hello ', +,
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] =>
[2] => array
(
[0] => 1
[1 ] => two
)
[3] => Apple
)
* *
This will be more effective, especially if it is compatible with many other languages, such as JavaScript. However, for complex objects, some information may be lost.
8, compressed string
When it comes to 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 take advantage of the gzcompress () and Gzuncompress () functions:
$string = "Lorem ipsum dolor sit amet, consectetur adipiscing. 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. 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 "; /* Prints Original size:800/echo "Compressed size:". Strlen ($compressed). "
\ n "; /* Prints Compressed size:418 *//GEtting it back $original = gzuncompress ($compressed);
The compression rate of this operation can reach about 50%. The other functions Gzencode () and Gzdecode () can achieve similar results by using different compression algorithms.
9. Registration Stop function
There is a function called register_shutdown_function () that lets you execute some specified code before a script finishes running. Suppose you need to capture some baseline statistics before the execution of the script, such as the length of time to run:
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 trivial and you just need to add the relevant code at the end of the script run. But if you call the exit () function, the code will not run. Also, if there is a fatal error, or if the script is terminated unexpectedly by the user, it may not run again. When you use the Register_shutdown_function () function, the code continues to execute regardless of whether 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. ";
}
English Manuscript: 9 useful PHP functions and Features you Need to Know Nettuts