Eight required PHP feature instance code
- 2020-10-23 20:55:50
- OfStack
Programmers who have worked on PHP should be aware that there are many built-in features in PHP that can help you develop PHP more easily. This article will share 8 essential PHP features, all of which are very useful, and I hope you can master them.
1. Pass any number of function arguments
2. Use glob() to find the file
3. Get memory usage information
4. Obtain CPU usage information
5. Get system constants
6. Generate id with only 1
7. Serialization
String compression
In.NET or JAVA programming, 1 generally takes a fixed number of function arguments, but PHP allows you to take any number of arguments. The following example shows you the default parameters of the PHP function:
// Function with two default arguments
function foo($arg1 = ", $arg2 = ") {
echo "arg1: $arg1\n";
echo "arg2: $arg2\n";
}
foo('hello','world');
/* The output :
arg1: hello
arg2: world
*/
foo();
/* The output :
arg1:
arg2:
*/
The following example is PHP The use of an indefinite parameter func_get_args() Methods:
// Yes, the parameter list is empty
function foo() {
// Gets an array of all the parameters passed in
$args = func_get_args();
foreach ($args as $k => $v) {
echo "arg".($k+1).": $v\n";
}
}
foo();
/* Nothing will be exported */
foo('hello');
/* The output
arg1: hello
*/
foo('hello', 'world', 'again');
/* The output
arg1: hello
arg2: world
arg3: again
*/
The name of most of the PHP functions can be understood literally, but when you look at glob(), you may not know what it is for. glob() and scandir() 1 can be used to find files, as shown below:
// Get all suffixes as PHP The file
$files = glob('*.php');
print_r($files);
/* The output :
Array
(
[0] => phptest.php
[1] => pi.php
[2] => post_output.php
[3] => test.php
)
*/
You can also find a variety of suffix names:
// take PHP Files and TXT file
$files = glob('*.{php,txt}', GLOB_BRACE);
print_r($files);
/* The 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 the path:
$files = glob('../images/a*.jpg');
print_r($files);
/* The output :
Array
(
[0] => ../images/apple.jpg
[1] => ../images/art.jpg
)
*/
If you want the 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
)
*/
The memory recovery mechanism of PHP is already very powerful. You can also use the PHP script to get the current memory usage by calling the memory_get_usage() function to get the current memory usage and calling the memory_ge
ak_usage() function to get the peak memory usage. The reference code is as follows:
echo "Initial: ".memory_get_usage()." bytes \n";
/* The output
Initial: 361400 bytes
*/
// The use of memory
for ($i = 0; $i < 100000; $i++) {
$array []= md5($i);
}
// delete 1 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";
/* The peak output
Peak: 13687072 bytes
*/
The usage of CPU can also be obtained by using getrusage() of PHP, which is not available under windows.
print_r(getrusage());
/* The 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
)
*/
The structure looks pretty obscure, unless you know CPU well. Here are some explanations: ru_oublock: block output operation ru_inblock: block input operation ru_msgsnd: sent message ES78en_ES76en: received message ru_maxrss: Maximum resident set size ru_ixrss: Total Shared memory size ru_idrss: Total non-shared memory size ru_minflt: page recycle ru_majflt: Page failure ru_ES89en: Received signal ru_nivcsw: active context switch ru_nswap: switching area ES96en_utime. tv_usec: User mode time (microseconds) ru_ES102en. tv_sec: ru_stime. tv_usec: system kernel time (microseconds) ru_ES112en. tv_sec: System kernel time? To see how much your script consumes CPU, we need to look at the values of "user mode time" and "system kernel time". The seconds and microseconds sections are provided separately, and you can divide the microseconds value by 1 million and add it to the seconds value to get the number of seconds with a fractional 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);
/* The output
User time: 0.011552
System time: 0
*/
It doesn't take up the time of the system. Let's take a look at the following example:
// loop 10 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);
/* The output
User time: 1.424592
System time: 0.004204
*/
This took about 14 seconds of CPU time, almost all of it the user's time because there were no system calls. Traditional time is the time that CPU spends executing kernel instructions on system calls. Here 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
System time: 1.675315
*/
The above example is even more expensive, CPU.
It provides useful system constants that let you get the current row number (132EN__), file (133EN__), table of contents (134en__), function name (135en__), class name (136en__), method name (137en__) and name-space (138en__), much like the C language.
Can we assume that these things are mainly used for debugging when, for example, we can use them with other include files? Per 142EN__ (of course, you can also use ___ after PHP 5.3 with the 1 example below.
// 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 included from
require_once(dirname(__FILE__) . '/config/database.php');
Here's the output of 1 debug using ___ 148EN__ to help you debug the programme:
// some code
// ...
my_debug("some debug message", __LINE__);
/* The output
Line 4: some debug message
*/
// some more code
// ...
my_debug("another debug message", __LINE__);
/* The output
Line 11: another debug message
*/
function my_debug($msg, $line) {
echo "Line $line: $msg\n";
}
6. Many friends of id use md5() to generate the number of only 1, but md5() has several disadvantages: 1. Unordering, resulting in the degradation of sorting performance in the database. 2, too long, need more storage space. In fact, PHP has a built-in function to generate the only 1 id, which is uniqid(). Here's how:
// generate unique string
echo uniqid();
/* The output
4bd67c947233e
*/
// generate another unique string
echo uniqid();
/* The output
4bd67c9472340
*/
This algorithm is generated based on the CPU timestamp, so the first few digits of id are one in a similar time period, which is also convenient for the sorting of id. If you want to better avoid repetition, you can prefix id, such as:
// The prefix
echo uniqid('foo_');
/* The output
foo_4bd67d6cd8b8f
*/
// There's more entropy
echo uniqid(",true);
/* The output
4bd67d6cd8b926.12135106
*/
// There are
echo uniqid('bar_',true);
/* The output
bar_4bd67da367b650.43684647
*/
When you need to save data to a database or file, you can use the serialize() and unserialize() methods in PHP to achieve serialization and deserialization, the code is as follows:
// 1 It's a complex array
$myvar = array(
'hello',
42,
array(1,'two'),
'apple'
);
// serialization
$string = serialize($myvar);
echo $string;
/* The 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";}
*/
// Antitone instantiated
$newvar = unserialize($string);
print_r($newvar);
/* The output
Array
(
[0] => hello
[1] => 42
[2] => Array
(
[0] => 1
[1] => two
)
[3] => apple
)
*/
How to serialize to json format? Rest assured, php has already made it for you. Users using php 5.2 or above can use json_encode() and json_decode() to serialize json format, the code is as follows:
// 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
)
*/
String compression When we talk about compression, we might think of file compression, in fact, strings can be compressed. PHP provides 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 pretium orci,
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 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";
/* Output original size
Original size: 800
*/
echo "Compressed size: ". strlen($compressed)."\n";
/* Output size after compression
Compressed size: 418
*/
// unzip
$original = gzuncompress($compressed);
It's almost 50 percent compression. You can also compress using the gzencode() and gzdecode() functions, but not using a different compression algorithm.
These are the 8 PHP features that are essential for development. Are they all useful?