8个有用的PHP函数总结
1. 注册停止函数有一个函数叫做 register_shutdown_function(),可以让你在整个脚本停时前运行代码。让我们看下面的一个示例:
// capture the start time$start_time = microtime(true);<br /><br />// do some stuff<br />// ...<br /><br />// display how long the script took<br />echo "execution took: ". (microtime(true) - $start_time)." seconds.";
上面这个示例只不过是用来计算某个函数运行的时间。
然后,如果你在函数中间调用 exit() 函数,那么你的最后的代码将不会被运行到。并且,如果该脚本在浏览器终止(用户按停止按钮),其也无法被运行。而当我们使用了register_shutdown_function()后,你的程序就算是在脚本被停止后也会被运行。
2. 使用 Glob() 查找文件很多PHP的函数都有一个比较长的自解释的函数名,但是,当你看到 glob() 的时候,你可能并不知道这个函数是用来干什么的,除非你对它已经很熟悉了。
你可以认为这个函数就好 scandir() 一样,他可以用来查找文件。
<p>// 取当前目录下的所有的PHP文件和TXT文件</p>$files = glob('*.{php,txt}', GLOB_BRACE);<br />print_r($files);<br />/* 输出:<br />Array<br />( <br />[0] => phptest.php <br />[1] => pi.php <br />[2] => post_output.php <br />[3] => test.php <br />[4] => log.txt <br />[5] => test.txt<br />)<br /><p>*/
3. 内存使用信息观察你程序的内存使用能够让你更好的优化你的代码。
PHP 是有垃圾回收机制的,而且有一套很复杂的内存管理机制。你可以知道你的脚本所使用的内存情况。要知道当前内存使用情况,你可以使用?memory_get_usage() 函数,如果你想知道使用内存的峰值,你可以调用 memory_get_peak_usage() 函数。
<p>echo "Initial: ".memory_get_usage()." bytes n";</p>/* 输出<br />Initial: 361400 bytes<br />*/<br /><br />// 使用内存<br />for ($i = 0; $i < 100000; $i++) { <br /> $array []= md5($i);<br />}<br /><br />// 删除一半的内存<br />for ($i = 0; $i < 100000; $i++) { <br /> unset($array[$i]);<br />}<br /> <br />echo "Final: ".memory_get_usage()." bytes n";<br />/* prints<br />Final: 885912 bytes<br />*/<br /><br />echo "Peak: ".memory_get_peak_usage()." bytes n";<br />/* 输出峰值<br />Peak: 13687072 bytes<br /><p>*/
4.CPU使用信息使用 getrusage() 函数可以让你知道CPU的使用情况。
注意,这个功能在Windows下不可用。
ru_oublock: 块输出操作
ru_inblock: 块输入操作ru_msgsnd: 发送的message
ru_msgrcv: 收到的message
ru_maxrss: 最大驻留集大小
ru_ixrss: 全部共享内存大小
ru_idrss:全部非共享内存大小
ru_minflt: 页回收
ru_majflt: 页失效
ru_nsignals: 收到的信号
ru_nvcsw: 主动上下文切换
ru_nivcsw: 被动上下文切换
ru_nswap: 交换区
ru_utime.tv_usec: 用户态时间 (microseconds)
ru_utime.tv_sec: 用户态时间(seconds)
ru_stime.tv_usec: 系统内核时间 (microseconds)
ru_stime.tv_sec: 系统内核时间?(seconds)5. 系统常量PHP 提供非常有用的系统常量 可以让你得到当前的行号 (__LINE__),文件 (__FILE__),目录 (__DIR__),函数名 (__FUNCTION__),类名(__CLASS__),方法名(__METHOD__) 和名字空间 (__NAMESPACE__),很像C语言。
我们可以以为这些东西主要是用于调试,当也不一定,比如我们可以在include其它文件的时候使用?__FILE__ (当然,你也可以在 PHP 5.3以后使用 __DIR__ )
6.生成唯一的ID有很多人使用 md5() 来生成一个唯一的ID,其实,PHP中有一个叫 uniqid() 的函数是专门用来干这个的:
<p>echo uniqid();</p>/* 输出<br />4bd67c947233e<br />*/<br />echo uniqid();<br />/* 输出<br />4bd67c9472340<br /><p>*/
可能你会注意到生成出来的ID前几位是一样的,这是因为sheng成器依赖于系统的时间,这其实是一个非常不错的功能,因为你是很容易为你的这些ID排序的。这点MD5是做不到的。
7. 序列化你是否会把一个比较复杂的数据结构存到数据库或是文件中?你并不需要自己去写自己的算法。
PHP早已为你做好了,其提供了两个函数:serialize() 和 unserialize():8. 字符串压缩当我们说到压缩,我们可能会想到文件压缩,其实,字符串也是可以压缩的。
PHP提供了 gzcompress() 和 gzuncompress() 函数:
<p>$string =</p>"Lorem ipsum dolor sit amet, consectetur<br />adipiscing elit. Nunc ut elit id mi ultricies<br />adipiscing. Nulla facilisi. Praesent pulvinar,<br />sapien vel feugiat vestibulum, nulla dui pretium orci,<br />non ultricies elit lacus quis ante. Lorem ipsum dolor<br />sit amet, consectetur adipiscing elit. Aliquam<br />pretium ullamcorper urna quis iaculis. Etiam ac massa<br />sed turpis tempor luctus. Curabitur sed nibh eu elit<br />mollis congue. Praesent ipsum diam, consectetur vitae<br />ornare a, aliquam a nunc. In id magna pellentesque<br />tellus posuere adipiscing. Sed non mi metus, at lacinia<br />augue. Sed magna nisi, ornare in mollis in, mollis<br />sed nunc. Etiam at justo in leo congue mollis.<br />Nullam in neque eget metus hendrerit scelerisque<br />eu non enim. Ut malesuada lacus eu nulla bibendum<br />id euismod urna sodales. ";<br /><br />$compressed = gzcompress($string);<br /><br />echo "Original size: ". strlen($string)."n";<br />/* 输出原始大小<br />Original size: 800<br />*/<br /><br />echo "Compressed size: ". strlen($compressed)."n";<br />/* 输出压缩后的大小<br />Compressed size: 418<br />*/<br /><br />// 解压缩<br /><p>$original = gzuncompress($compressed);
几乎有50% 压缩比率。
同时,你还可以使用?gzencode() 和 gzdecode() 函数来压缩,只不用其用了不同的压缩算法。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to optimize the lazy loading effect of images through PHP functions? With the development of the Internet, the number of images in web pages is increasing, which puts pressure on page loading speed. In order to improve user experience and reduce loading time, we can use image lazy loading technology. Lazy loading of images can delay the loading of images. Images are only loaded when the user scrolls to the visible area, which can reduce the loading time of the page and improve the user experience. When writing PHP web pages, we can optimize the lazy loading effect of images by writing some functions. Details below

How to reduce memory usage through PHP functions. In development, memory usage is a very important consideration. If a large amount of memory is used in a program, it may cause slowdowns or even program crashes. Therefore, reasonably managing and reducing memory usage is an issue that every PHP developer should pay attention to. This article will introduce some methods to reduce memory usage through PHP functions, and provide specific code examples for readers' reference. Use the unset() function to release variables in PHP. When a variable is no longer needed, use

PHP function introduction—curl_multi_getcontent(): Get the content of a cURL session. In PHP development, we often need to request data from other servers through the network. And cURL (ClientURL) is a powerful PHP extension library used for network communication in PHP. cURL provides a series of functions, one of which is curl_multi_getcontent(), which is used to obtain the content of a cURL session.

PHPDeprecated: Functionereg_replace()isdeprecated-Solution When developing in PHP, we often encounter the problem of some functions being declared deprecated. This means that in the latest PHP versions, these functions may be removed or replaced. One common example is the ereg_replace() function. ereg_replace

PHP image processing functions are a set of functions specifically used to process and edit images. They provide developers with rich image processing functions. Through these functions, developers can implement operations such as cropping, scaling, rotating, and adding watermarks to images to meet different image processing needs. First, I will introduce how to use PHP image processing functions to achieve image cropping function. PHP provides the imagecrop() function, which can be used to crop images. By passing the coordinates and size of the cropping area, we can crop the image

PHP function introduction: strtr() function In PHP programming, the strtr() function is a very useful string replacement function. It is used to replace specified characters or strings in a string with other characters or strings. This article will introduce the usage of strtr() function and give some specific code examples. The basic syntax of the strtr() function is as follows: strtr(string$str, array$replace) where $str is the original word to be replaced.

PHP functions have similarities with functions in other languages, but also have some unique features. Syntactically, PHP functions are declared with function, JavaScript is declared with function, and Python is declared with def. In terms of parameters and return values, PHP functions accept parameters and return a value. JavaScript and Python also have similar functions, but the syntax is different. In terms of scope, functions in PHP, JavaScript and Python all have global or local scope. Global functions can be accessed from anywhere, and local functions can only be accessed within their declaration scope.

The performance of different PHP functions is crucial to application efficiency. Functions with better performance include echo and print, while functions such as str_replace, array_merge, and file_get_contents have slower performance. For example, the str_replace function is used to replace strings and has moderate performance, while the sprintf function is used to format strings. Performance analysis shows that it only takes 0.05 milliseconds to execute one example, proving that the function performs well. Therefore, using functions wisely can lead to faster and more efficient applications.
