Home>

Programmers in php development should be clear,There are many built-in functions in php,Mastered them,Can help you be more handy when doing PHP development,This article will share 8 necessary PHP functions for development, all of them are very practical,I hope you can master it.

1. Pass any number of function parameters

In programming in .net or java, 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 of a php function:

//function with two default parameters
function foo ($arg1=", $arg2 =") {
echo "arg1:$arg1 \ n";
echo "arg2:$arg2 \ n";
}
foo ("hello", "world");
/* Output:
arg1:hello
arg2:world
* /
foo ();
/* Output:
arg1:
arg2:
* /

The following example is the indefinite parameter usage of php,It uses the func_get_args () method:

//yes, the parameter list is empty
function foo () {
//Get an array of all incoming parameters
$args=func_get_args ();
foreach ($args as $k =>$v) {
echo "arg". ($k + 1). ":$v \ n";
}
}
foo ();
/* Nothing is output * /
foo ("hello");
/* Output
arg1:hello
* /
foo ("hello", "world", "again");
/* Output
arg1:hello
arg2:world
arg3:again
* /

Find files using glob ()The function name of most php functions can be understood literally,But when you see glob (), you may not know what it is used for,In fact, glob () and scandir () can be used to find files.Consider the following usage:

//Get all files with suffix php
$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 file and txt file
$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
13.
)
* /

You can also add the path:

$files=glob ("../images/a * .jpg");
print_r ($files);
/* Output:
array
(
[0] =>../images/apple.jpg
[1] =>../images/art.jpg
)
* /

If i want to get 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
)
* /

Get memory usage information

PHP's memory reclamation mechanism is already very powerful,You can also use php script to get the current memory usage,Call the memory_get_usage () function to get the current memory usage,Call the memory_get_peak_usage () function to get the peak value of memory usage.The reference code is as follows:

echo "initial:" .memory_get_usage (). "bytes \ n";
/* Output
initial:361400 bytes
* /
//use memory
for ($i=0;$i<100000;$i ++) {
$array []=md5 ($i);
}
//delete 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.Get CPU usage information

Got memory usage,You can also use php's getrusage () to get cpu usage,This method is not available under windows.

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 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 to send

ru_msgrcv:received message

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 invalid

ru_nsignals:received signals

ru_nvcsw:Active context switch

ru_nivcsw:passive context switch

ru_nswap:swap area

ru_utime.tv_usec:user mode time (microseconds)

ru_utime.tv_sec:user mode time (seconds)

ru_stime.tv_usec:system kernel time (microseconds)

ru_stime.tv_sec:system kernel time (seconds)

To see how many CPUs your script is consuming, we need to look at the values ​​of "User Time" and "System Kernel Time". The seconds and microseconds are provided separately,You can divide the microsecond value by 1 million and add it to the value of the second,You can 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);
/* Output
user time:0.011552
system time:0
* /
sleep does not take up system time,We can 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);
/* Output
user time:1.424592
system time:0.004204
* /

This took about 14 seconds of cpu time, almost all of it was user time,Because there is no system call.

System time is the time the CPU spends executing kernel instructions on system calls.Below 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
* /

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 think that these things are mainly used for debugging,When is not necessarily,For example, we can use?__ file__ when including other files (of course, you can also use __dir__ after PHP 5.3), here is an example.

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

The following is the use of __line__ to output some 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 unique id

Many friends use md5 () to generate unique numbers,But md5 () has several disadvantages:1. Out of order, causing the sorting performance in the database to decrease.2. It is too long and requires more storage space.In fact, PHP comes with a function to generate a unique id. This function is uniqid (). Here is the usage:

//generate unique string
echo uniqid ();
/* Output
4bd67c947233e
* /
//generate another unique string
echo uniqid ();
/* Output
4bd67c9472340
* /

The algorithm is generated based on the cpu timestamp,So in a similar time period,The first few digits are the same,This is also convenient for sorting ids. If i want to better avoid duplicatesYou can prefix the id,Such as:

//prefix
echo uniqid ("foo_");
/* Output
foo_4bd67d6cd8b8f
* /
//have more entropy
echo uniqid (", true);
/* Output
4bd67d6cd8b926.12135106
* /
//both
echo uniqid ("bar _", true);
/* Output
bar_4bd67da367b650.43684647
* /

7.Serializationphp serialization function you may use more,It ’s more common,When you need to store data in a database or file,You can use serialize () and unserialize () methods in php to implement serialization and deserialization,code show as below:

//a complex array
$myvar=array (
"hello",42,array (1, "two"),"apple"
);
//Serialization
$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";}
* /
//reverse order instantiation
$newvar=unserialize ($string);
print_r ($newvar);
/* Output
array
(
[0] =>hello
[1] =>42
[2] =>array
(
[0] =>1
[1] =>two
)
[3] =>apple
)
* /

How to serialize into json format, rest assured, php has already done it for you,Users using PHP 5.2 and above can use the json_encode () and json_decode () functions to implement serialization in json format.code show as below:

//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 compressionWhen we talk about compression,We might think of file compression,In fact, strings are also compressible.php provides 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 compressed size
compressed size:418
* /
//unzip
$original=gzuncompress ($compressed);

Almost 50%compression ratio.At the same time, you can also use gzencode () and gzdecode () functions to compress,Just don't use a different compression algorithm.

php
  • Previous AngularJS basic ng-href instruction usage
  • Next A complete example of the provincial, city, and county three-level linkage menu effect implemented by jQuery