8 essential functions for PHP development

怪我咯
Release: 2023-03-11 22:10:01
Original
1270 people have browsed it

Programmers who develop PHP should know that there are many built-in functions in PHP. Mastering them can help you become more comfortable in PHP development. This article will share 8 essential PHP functions for development. All of them are very practical and I hope all PHP developers can master them.

1. Pass any number of function parameters
In .NET or J***A programming, general functions The number of parameters is fixed, but PHP allows you to use any number of parameters. The following example shows you the default parameters of PHP functions:

// 两个默认参数的函数 
function foo($arg1 = ”, $arg2 = ”) { 
echo “arg1: $arg1\n”; 
echo “arg2: $arg2\n”; 
} 
foo(‘hello','world'); 
/* 输出:
arg1: hello
arg2: world
*/ 
foo(); 
/* 输出:
arg1:
arg2:
*/
Copy after login

The following example is PHP's variable parameter usage, which uses the func_get_args() method:

// 是的,形参列表为空 
function foo() { 
// 取得所有的传入参数的数组 
$args = func_get_args(); 
foreach ($args as $k => $v) { 
echo “arg”.($k+1).”: $v\n”; 
} 
} 
foo(); 
/* 什么也不会输出 */ 
foo(‘hello'); 
/* 输出
arg1: hello
*/ 
foo(‘hello', ‘world', ‘again'); 
/* 输出
arg1: hello
arg2: world
arg3: again
*/
Copy after login

2. Use glob() to find files
The function names of most PHP functions can literally understand their purpose, but when you see glob(), you may not know it. What is this used for? In fact, glob() is the same as scandir() and can be used to find files. Please see the following usage:

// 取得所有的后缀为PHP的文件 
$files = glob(‘*.php'); 
print_r($files); 
/* 输出:
Array
(
[0] => phptest.php
[1] => pi.php
[2] => post_output.php
[3] => test.php
)
*/
 
你还可以查找多种后缀名:
// 取PHP文件和TXT文件 
$files = glob(‘*.{php,txt}', GLOB_BRACE); 
print_r($files); 
/* 输出:
Array
(
[0] => phptest.php
[1] => pi.php
[2] => post_output.php
[3] => test.php
[4] => log.txt
[5] => test.txt
13.
)
*/
Copy after login

You can also add the path:

$files = glob(‘../images/a*.jpg'); 
print_r($files); 
/* 输出:
Array
(
[0] => ../images/apple.jpg
[1] => ../images/art.jpg
)
*/
Copy after login

If you 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
)
*/
Copy after login

3. Get memory usage information

PHP's memory recycling mechanism is already very powerful. You can also use PHP scripts to obtain the current memory usage. Call the memory_get_usage() function to obtain the current memory usage. Call the memory_get_peak_usage() function. Get the peak memory usage. The reference code is as follows:

echo “Initial: “.memory_get_usage().” bytes \n”; 
/* 输出
Initial: 361400 bytes
*/ 
// 使用内存 
for ($i = 0; $i < 100000; $i++) { 
$array []= md5($i); 
} 
// 删除一半的内存 
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”; 
/* 输出峰值
Peak: 13687072 bytes
*/
Copy after login

4. Obtain CPU usage information

To obtain memory usage, you can also use PHP’s getrusage() Get CPU usage, this method is not available under windows.

print_r(getrusage()); 
/* 输出
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
)
*/
Copy after login

This structure seems very obscure, unless you know the CPU very well. Here are some explanations:

ru_oublock: block output operation

ru_inblock: block input operation

ru_msgsnd: sent message

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 invalidation

ru_nsignals: Signals received

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 much CPU your script consumes, we need to look at the "user mode time" and The value of "System Kernel Time". The seconds and microseconds parts are provided separately. 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[&#39;ru_utime.tv_sec&#39;] + 
$data[&#39;ru_utime.tv_usec&#39;] / 1000000); 
echo “System time: “. 
($data[&#39;ru_stime.tv_sec&#39;] + 
$data[&#39;ru_stime.tv_usec&#39;] / 1000000); 
/* 输出
User time: 0.011552
System time: 0
*/
sleep是不占用系统时间的,我们可以来看下面的一个例子: 
// loop 10 million times (busy) 
for($i=0;$i<10000000;$i++) { 
} 
$data = getrusage(); 
echo “User time: “. 
($data[&#39;ru_utime.tv_sec&#39;] + 
$data[&#39;ru_utime.tv_usec&#39;] / 1000000); 
echo “System time: “. 
($data[&#39;ru_stime.tv_sec&#39;] + 
$data[&#39;ru_stime.tv_usec&#39;] / 1000000); 
/* 输出
User time: 1.424592
System time: 0.004204
*/
Copy after login

This took about 14 seconds of CPU time, almost all of it user time since there were no system calls.
System time is the time the 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[&#39;ru_utime.tv_sec&#39;] + 
$data[&#39;ru_utime.tv_usec&#39;] / 1000000); 
echo “System time: “. 
($data[&#39;ru_stime.tv_sec&#39;] + 
$data[&#39;ru_stime.tv_usec&#39;] / 1000000); 
/* prints
User time: 1.088171
System time: 1.675315
*/
Copy after login

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 C language.
We can think that these things are mainly used for debugging, but 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&#39;s path 
// it may cause problems when running scripts from different directories 
require_once(‘config/database.php&#39;); 
// this is always relative to this file&#39;s path 
// no matter where it was included from 
require_once(dirname(FILE) . ‘/config/database.php&#39;);
Copy after login

The following is using LINE to output some debug information, which will help you debug the program:

// some code 
// … 
my_debug(“some debug message”, LINE); 
/* 输出
Line 4: some debug message
*/ 
// some more code 
// … 
my_debug(“another debug message”, LINE); 
/* 输出
Line 11: another debug message
*/ 
function my_debug($msg, $line) { 
echo “Line $line: $msg\n”;
}
Copy after login

6. Generate a unique id
Many friends use md5() to generate unique numbers, but md5() has several shortcomings: 1. Disorder, resulting in reduced sorting performance in the database. 2. Too long and requires more storage space. In fact, PHP comes with a function to generate a unique id. This function is uniqid(). The following is the usage:

// generate unique string 
echo uniqid(); 
/* 输出
4bd67c947233e
*/ 
// generate another unique string 
echo uniqid(); 
/* 输出
4bd67c9472340
*/
Copy after login

This algorithm is generated based on the CPU timestamp, so in a similar time period, the first few digits of the ID are the same, which is also convenient for sorting the ID. If you If you want to better avoid duplication, you can add a prefix before the id, such as:

// 前缀 
echo uniqid(‘foo_&#39;); 
/* 输出
foo_4bd67d6cd8b8f
*/ 
// 有更多的熵 
echo uniqid(”,true); 
/* 输出
4bd67d6cd8b926.12135106
*/ 
// 都有 
echo uniqid(‘bar_&#39;,true); 
/* 输出
bar_4bd67da367b650.43684647
*/
Copy after login

7. Serialization
You may use the PHP serialization function more often. , is also relatively common. When you need to save data to a database or file, you can use the serialize() and unserialize() methods in PHP to implement serialization and deserialization. The code is as follows:

// 一个复杂的数组 
$myvar = array( 
‘hello&#39;, 
42, 
array(1,&#39;two&#39;), 
‘apple&#39; 
); 
// 序列化 
$string = serialize($myvar); 
echo $string; 
/* 输出
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”;}
*/ 
// 反序例化 
$newvar = unserialize($string); 
print_r($newvar); 
/* 输出
Array
(
[0] => hello
[1] => 42
[2] => Array
(
[0] => 1
[1] => two
)
[3] => apple
)
*/
Copy after login

How to serialize into json format? Don’t worry, PHP has already done it for you. Users using PHP 5.2 or above can use the json_encode() and json_decode() functions to serialize json format. The code is as follows:

// a complex array
$myvar = array( 
‘hello&#39;, 
42, 
array(1,&#39;two&#39;), 
‘apple&#39; 

); 
// 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
)
*/
Copy after login

8、字符串压缩
当我们说到压缩,我们可能会想到文件压缩,其实,字符串也是可以压缩的。PHP提供了 gzcompress() 和gzuncompress() 函数:

$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”; 
/* 输出原始大小
Original size: 800
*/ 
echo “Compressed size: “. strlen($compressed).”\n”; 
/* 输出压缩后的大小
Compressed size: 418
*/ 
// 解压缩 
$original = gzuncompress($compressed);
Copy after login

几乎有50% 压缩比率。同时,你还可以使用 gzencode() 和 gzdecode() 函数来压缩,只不用其用了不同的压缩算法。  

以上就是8个开发必备的PHP功能,是不是都很实用呢?

The above is the detailed content of 8 essential functions for PHP development. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template