8 essential PHP function development_PHP tutorial

WBOY
Release: 2016-07-13 10:38:56
Original
873 people have browsed it

Programmers who have done PHP development 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, each of which They are all very practical and I hope all PHP developers can master them.​ ​ 8 essential PHP function development_PHP tutorial

​ 1. Pass any number of function parameters ​ In .NET or JAVA programming, the number of function parameters is generally fixed, but PHP allows you to use any number of parameters.The following example shows you the default parameters of a PHP function: ​ Php code

  1. // Function with two default parameters
  2. function foo($arg1 = ”, $arg2 = ”) {
  3. echo “arg1: $arg1n”;
  4. echo “arg2: $arg2n”;
  5. }
  6. foo(‘hello’,’world’);
  7. /* Output:
  8. arg1: hello
  9. arg2: world
  10. */
  11. foo();
  12. /* Output:
  13. arg1:
  14. arg2:
  15. */
  16. The following example is the usage of variable parameters in PHP, which uses the [url=http://us2.php.net/manual/en/function.func-get-args.php]func_get_args()[/url] method:
  17. // Yes, the parameter list is empty
  18. function foo() {
  19. // Get the array of all incoming parameters
  20. $args = func_get_args();
  21. foreach ($args as $k => $v) {
  22. echo “arg”.($k+1).”: $vn”;
  23. }
  24. }
  25. foo();
  26. /* Nothing will be output */
  27. foo(‘hello’);
  28. /* Output
  29. arg1: hello
  30. */
  31. foo(‘hello’, ‘world’, ‘again’);
  32. /* Output
  33. arg1: hello
  34. arg2: world
  35. arg3: again
  36. */
​ ​ 2. Use glob() to find files ​ The function names of most PHP functions can understand their purpose literally, but when you see glob(), you may not know what it is used for. In fact, glob() is the same as scandir(). It can be used to find files, please see the usage below: ​ Php code
  1. // Get all files with the suffix PHP
  2. $files = glob(‘*.php’);
  3. print_r($files);
  4. /* Output:
  5. Array
  6. (
  7. [0] => phptest.php
  8. [1] => pi.php
  9. [2] => post_output.php
  10. [3] => test.php
  11. )
  12. */
​ You can also search for various suffixes: ​ Php code
  1. // Get PHP files and TXT files
  2. $files = glob(‘*.{php,txt}’, GLOB_BRACE);
  3. print_r($files);
  4. /* Output:
  5. Array
  6. (
  7. [0] => phptest.php
  8. [1] => pi.php
  9. [2] => post_output.php
  10. [3] => test.php
  11. [4] => log.txt
  12. [5] => test.txt
  13. )
  14. */
​ You can also add the path: ​ Php code
  1. $files = glob(‘../images/a*.jpg’);
  2. print_r($files);
  3. /* Output:
  4. Array
  5. (
  6. [0] => ../images/apple.jpg
  7. [1] => ../images/art.jpg
  8. )
  9. */
​ ​ If you want to get the absolute path, you can call the realpath() function: ​ Php code
  1. $files = glob(‘../images/a*.jpg’);
  2. //applies the function to each array element
  3. $files = array_map(‘realpath’,$files);
  4. print_r($files);
  5. /* output looks like:
  6. Array
  7. (
  8. [0] => C:wampwwwimagesapple.jpg
  9. [1] => C:wampwwwimagesart.jpg
  10. )
  11. */
​ ​ 3. Obtain 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, and call the memory_get_peak_usage() function to obtain the peak memory usage. The reference code is as follows: ​ Php code
  1. echo “Initial: “.memory_get_usage().” bytes n”;
  2. /* Output
  3. Initial: 361400 bytes
  4. */
  5. //Use memory
  6. for ($i = 0; $i < 100000; $i++) {
  7. $array []= md5($i);
  8. }
  9. // Delete half of the memory
  10. for ($i = 0; $i < 100000; $i++) {
  11. unset($array[$i]);
  12. }
  13. echo “Final: “.memory_get_usage().” bytes n”;
  14. /* prints
  15. Final: 885912 bytes
  16. */
  17. echo “Peak: “.memory_get_peak_usage().” bytes n”;
  18. /* Output peak value
  19. Peak: 13687072 bytes
  20. */
​ ​ 4. Get CPU usage information ​ After obtaining the memory usage, you can also use PHP's getrusage() to obtain the CPU usage. This method is not available under Windows.    Php代码 
  1. print_r(getrusage());  
  2. /* 输出 
  3. Array 
  4. [ru_oublock] => 0 
  5. [ru_inblock] => 0 
  6. [ru_msgsnd] => 2 
  7. [ru_msgrcv] => 3 
  8. [ru_maxrss] => 12692 
  9. [ru_ixrss] => 764 
  10. [ru_idrss] => 3864 
  11. [ru_minflt] => 94 
  12. [ru_majflt] => 0 
  13. [ru_nsignals] => 1 
  14. [ru_nvcsw] => 67 
  15. [ru_nivcsw] => 4 
  16. [ru_nswap] => 0 
  17. [ru_utime.tv_usec] => 0 
  18. [ru_utime.tv_sec] => 0 
  19. [ru_stime.tv_usec] => 6269 
  20. [ru_stime.tv_sec] => 0 
  21. */  
    这个结构看上出很晦涩,除非你对CPU很了解。下面一些解释: 
  • 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)
  要看到你的脚本消耗了多少CPU,我们需要看看“用户态的时间”和“系统内核时间”的值。秒和微秒部分是分别提供的,您可以把微秒值除以100万,并把它添加到秒的值后,可以得到有小数部分的秒数。    Php代码 
  1. // sleep for 3 seconds (non-busy)  
  2. sleep(3);  
  3. $data = getrusage();  
  4. echo “User time: “.  
  5. ($data['ru_utime.tv_sec'] +  
  6. $data['ru_utime.tv_usec'] / 1000000);  
  7. echo “System time: “.  
  8. ($data['ru_stime.tv_sec'] +  
  9. $data['ru_stime.tv_usec'] / 1000000);  
  10. /* 输出 
  11. User time: 0.011552 
  12. System time: 0 
  13. */  
  sleep是不占用系统时间的,我们可以来看下面的一个例子:    Php代码 
  1. // loop 10 million times (busy)  
  2. for($i=0;$i<10000000;$i++) {  
  3. }  
  4. $data = getrusage();  
  5. echo “User time: “.  
  6. ($data['ru_utime.tv_sec'] +  
  7. $data['ru_utime.tv_usec'] / 1000000);  
  8. echo “System time: “.  
  9. ($data['ru_stime.tv_sec'] +  
  10. $data['ru_stime.tv_usec'] / 1000000);  
  11. /* 输出 
  12. User time: 1.424592 
  13. System time: 0.004204 
  14. */  
      这花了大约14秒的CPU时间,几乎所有的都是用户的时间,因为没有系统调用。  系统时间是CPU花费在系统调用上的上执行内核指令的时间。Here is an example: ​ Php code
  1. $start = microtime(true);
  2. // keep calling microtime for about 3 seconds
  3. while(microtime(true) – $start < 3) {
  4. }
  5. $data = getrusage();
  6. echo “User time: “.
  7. ($data['ru_utime.tv_sec'] +
  8. $data['ru_utime.tv_usec'] / 1000000);
  9. echo “System time: “.
  10. ($data['ru_stime.tv_sec'] +
  11. $data['ru_stime.tv_usec'] / 1000000);
  12. /* prints
  13. User time: 1.088171
  14. System time: 1.675315
  15. */
​ ​ 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.​ ​ Php code
  1. // this is relative to the loaded script’s path
  2. // it may cause problems when running scripts from different directories
  3. require_once(‘config/database.php’);
  4. // this is always relative to this file’s path
  5. // no matter where it was included from
  6. require_once(dirname(__FILE__) . ‘/config/database.php’);
​ The following is using __LINE__ to output some debug information, which will help you debug the program: ​ Php code
  1. // some code
  2. // … 
  3. my_debug(“some debug message”, __LINE__);
  4. /* Output
  5. Line 4: some debug message
  6. */
  7. // some more code
  8. // … 
  9. my_debug(“another debug message”, __LINE__);
  10. /* Output
  11. Line 11: another debug message
  12. */
  13. function my_debug($msg, $line) {
  14. echo “Line $line: $msgn”;
  15. }
​ ​ 6. Generate unique id ​ Many friends use md5() to generate unique numbers, but md5() has several shortcomings: 1. Disorder, which leads to a decrease in 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().Here’s how to use it: ​ Php code
  1. // generate unique string
  2. echo uniqid();
  3. /* Output
  4. 4bd67c947233e
  5. */
  6. // generate another unique string
  7. echo uniqid();
  8. /* Output
  9. 4bd67c9472340
  10. */
​ ​ This algorithm is generated based on CPU timestamps, so in similar time periods, the first few digits of the ID are the same, which also facilitates the sorting of IDs. If you want to better avoid duplication, you can add a prefix before the ID. ,like: ​ Php code
  1. // Prefix
  2. echo uniqid(‘foo_’);
  3. /* Output
  4. foo_4bd67d6cd8b8f
  5. */
  6. // There is more entropy
  7. echo uniqid(”,true);
  8. /* Output
  9. 4bd67d6cd8b926.12135106
  10. */
  11. // All
  12. echo uniqid(‘bar_’,true);
  13. /* Output
  14. bar_4bd67da367b650.43684647
  15. */
​ ​ 7. Serialization ​ You may use PHP serialization function more and more commonly. 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: ​ Php code
  1. // A complex array
  2. $myvar = array(
  3. ‘hello’,
  4. 42,
  5. array(1,’two’),
  6. ‘apple’
  7. );
  8. // Serialization
  9. $string = serialize($myvar);
  10. echo $string;
  11. /* Output
  12. 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";}
  13. */
  14. //Desequential instantiation
  15. $newvar = unserialize($string);
  16. print_r($newvar);
  17. /* Output
  18. Array
  19. (
  20. [0] => hello
  21. [1] => 42
  22. [2] => Array
  23. (
  24. [0] => 1
  25. [1] => two
  26. )
  27. [3] => apple
  28. )
  29. */
​ ​ 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: ​ Php code
  1. // a complex array
  2. $myvar = array(
  3. ‘hello’,
  4. 42,
  5. array(1,’two’),
  6. ‘apple’
  7. );
  8. // convert to a string
  9. $string = json_encode($myvar);
  10. echo $string;
  11. /* prints
  12. ["hello",42,[1,"two"],"apple"]
  13. */
  14. // you can reproduce the original variable
  15. $newvar = json_decode($string);
  16. print_r($newvar);
  17. /* prints
  18. Array
  19. (
  20. [0] => hello
  21. [1] => 42
  22. [2] => Array
  23. (
  24. [0] => 1
  25. [1] => two
  26. )
  27. [3] => apple
  28. )
  29. */
​ ​ 8. String compression ​ When we talk about compression, we may think of file compression. In fact, strings can also be compressed.PHP provides gzcompress() and gzuncompress() functions:    Php code 
  1. $string = 
  2. "The truth is that the pain itself is good, it will be successful.
  3. customer service. Now let's get it out of my hands
  4. coaching There is no easy way. It's a pillow,
  5. wisdom or flight of the vestibule, I will not give the price of the hospital,
  6. He did not raise the lake as much as before. Thank you very much.
  7. let it be good, it will be able to attract the customer. Some
  8. the price of any body that is targeted. Yes, and mass
  9. but it was an ugly time of mourning. I'm sorry but I'm sorry
  10. soft homework It is the very day, it will be the result of life
  11. to decorate a, something from now In that great and pushing
  12. to lay the ground But not my fear, but Lacinia
  13. advertise But unless it's big, decorate it in soft, soft
  14. but now. Even at just the right time for homework.  
  15. There is no need to fear chocolate and chocolate
  16. not football. To drink the unsavory lake of football
  17. that euismod urn members “;  
  18. $compressed = gzcompress($string);  
  19. echo "Original size:". strlen($string).”n”;  
  20. /* output original size
  21. Original size: 800
  22. */
  23. echo "Compressed size:". strlen($compressed)."n";  
  24. /* output 剧情后 size
  25. Compressed size: 418
  26. */
  27. // 解剧情  
  28. $original = gzuncompress($compressed);  
    At the same time, you can also use gzencode() and gzdecode() function to compress, only use different compression algorithms.    Above is the 8个安全必备的PHP function, is it not very practical?

原文出处:8个安全必备的PHP function

http://www.bkjia.com/PHPjc/735057.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/735057.htmlTechArticle 做过PHP 可件的电影员光可以这些,PHP has a lot of built-in functions, grasp all of them, it can help You're in the middle of PHP development...
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