8 Essential PHP features to develop _php tips

Source: Internet
Author: User
Tags glob md5 memory usage php script serialization unique id cpu usage

PHP developers should be aware that PHP has a lot of built-in functions, mastered them, can help you do in PHP development more handy, this article will share 8 development of the necessary PHP features, all are very practical, I hope you can master PHP developers.

1, pass any number of function parameters
We're in. NET or Java programming, 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 for PHP functions:

function of two default parameters 
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:
* * 

The following example is the indefinite parameter usage of PHP, which uses the Func_get_args () method:

Yes, the parameter list is an empty 
function foo () { 
//Gets an array of all incoming arguments 
$args = Func_get_args (); 
foreach ($args as $k => $v) { 
echo "arg". ( $k + 1). ": $v \ n"; 
} 
} 
Foo (); 
* * What will not output 
/foo (' Hello '); 
/*
output
Arg1:hello 
/foo (' Hello ', ' world ', ' again '); 
/* Output
Arg1:hello
arg2:world
arg3:again
* *
 
 

2. Use Glob () to find files
most of the function names of PHP functions can literally understand their purpose, but when you see Glob (), you may not know what this is for, but Glob () and Scandir () can be used to find files, see the following usage:

Get all the suffixes for php file 
$files = glob (' *.php '); 
Print_r ($files); 
/* Output:
Array
(
[0] => phptest.php
[1] => pi.php
[2] => post_output.php
[3] => test.php
)
* *
 
You can also look for multiple suffix names:
//php files 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
.
)
*/
 

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. Get Memory usage information
PHP's memory recycling mechanism is already very powerful, you can also use the PHP script to get the current memory usage, call the Memory_get_usage () function to get the memory usage, call the Memory_get_peak_usage () function to get the peak 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"; 
/* Output Peak
peak:13687072 bytes
* *

4. Get CPU usage information
Get memory usage, or use PHP's Getrusage () to get CPU usage, which 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] =>
[Ru_majflt] => 0
[Ru_nsignals] = > 1
[RU_NVCSW] =>
[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. The following explanations are:
ru_oublock: Block output Operation
Ru_inblock: Block input
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 size
Ru_minflt: Page Recycling
Ru_majflt: Page invalidation
Ru_nsignals: 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 "User state Time" and "system kernel Time" values. 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 is not taking up 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:

$start = Microtime (true); 
Keep calling microtime for about 3 seconds while 
Microtime (True) – $start < 3) { 
} 
$data = Getrusage (); C5/>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 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.

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

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
Many friends use MD5 () to generate a unique number, but MD5 () has several disadvantages: 1, disorderly, resulting in the database sorting performance degradation. 2, too long, need 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 based on the CPU time stamp to generate, so in a similar time period, the number of the first few are the same, which also facilitates the ordering of IDs, if you want to better avoid duplication, you can prefix the ID before, such as:

Prefix 
echo uniqid (' Foo_ '); 
/* Output
foo_4bd67d6cd8b8f
// 
/There is more entropy 
echo uniqid (", true); 
/* Output
4bd67d6cd8b926.12135106
// 
/all have 
echo uniqid (' Bar_ ', true); 
/* Output
bar_4bd67da367b650.43684647
* *

7. Serialization of
PHP Serialization features you may use more, but also more common, when you need to save data to the database or file is, you can use PHP serialize () and Unserialize () method to achieve serialization and deserialization, the code is as follows:

A complex array of 
$myvar = array ( 
' Hello ', 
two, 
array (1, ' n '), 
' 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 sequence 
$newvar = Unserialize ($string); 
Print_r ($newvar); 
/* Output
array
(
[0] => Hello
[1] =>
[2] => array
(
[0] => 1
[1] =& Gt Two
)
[3] => Apple
)
* * 

How to serialize to the JSON format, rest assured that PHP has been done for you, users using PHP version 5.2 or above can use the Json_encode () and Json_decode () functions to achieve the serialization of JSON format, the code is as follows:

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
)
* *

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:

$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 "; /* Output Original size Original size:800/echo "Compressed size:". Strlen ($compressed). " 
\ n "; /* Output Compressed size CompressEd size:418 *//decompression $original = gzuncompress ($compressed);
  

The

has almost 50% compression ratios. At the same time, you can use the Gzencode () and the Gzdecode () function to compress, using only a different compression algorithm. &NBSP;&NBSP
above is 8 development essential PHP function, is not all very practical?

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.