PHP Small Record

Source: Internet
Author: User
Tags http post php switch switch case server memory

Positive Framework (heavy use)thinkphp (partially used) cakephpyii (rarely used) [one] function1: function declaration: The first line of each function is the beginning of the function, with the declaration function of the keyword function, function name and parameter list are composed of three parts. 2: Function invocation: Functions table () {                                                ... ....                                                };table (); (table () function call, can be in front, also in the rear)3: Declare and apply various forms of PHP functions:(1) General parameter function: string example (string name, int age, double)        (2) function of pseudo-type parameter: Mixed funname (mixed $args) or number funname (number $args)        (3) function of reference parameter: void Funname (array $arg)        (4) function of default parameter: Mixed Funname (string name[,string value[,int expire])        (5)variable parameter functions: Mixed Funname (String arg1[,string ...]) Use pseudo type "..." in parameter list description        (6) Return function: Mixed Funname (callback arg)//Use pseudo type callback description in parameter list "1" variable function "2" with the Call_user_func_array () function to customize the return function: Mixed Call_user_func_array (callback Function,array Param_arr) (Note: first Parameters because of using pseudo-type parameterscallback  So this parameter needs to be a string that represents the function name to invoke, the second parameter is an array type parameter that represents the parameter list, which in turn is passed to the function to be called.   [II] arrays         1: Arrays: (1) Direct assignment of declared array: $ array variable name [subscript]= data content           & nbsp             (2) Create a new array using the array () language structure: $ array variable name =arry (Key1 =>value1, key2=>value2.....keyn= >valuen);        2: Array traversal: the Mysql_fetch_row () function takes a row from the result set as an enumeration function group return;               (1) For statement looping through arrays                       &NBSP ;       $contact = Array (                        & nbsp                       The array (...)                                  &NBS P               The array (...).      &NBsp                          ,         &NB Sp        );                          and nbsp     for ();                (2)  foreach statement traversal array: foreach (Array_ Expression as $calue) {loop body} or foreach (array_expression as $key = + $value) {loop body}            &N Bsp   (3)   combined use list (), each () and Iwile loop to iterate through an array         3: An array of related processing functions           & nbsp     (1)   array key/merit action function                         &NBSP The function of "1" array_values () is to return the values of all the elements in the array.                           2 The function of the Array_krys () function is to return all keys in the array Name.                           "3" function IThe function of the N_array () function is to check if there is a value in the array, that is, to search for the given value in the array                       &NBSP ;   4 The function of the ARRAY_FILP () function is to reverse the order of elements in the original array, create a new array, and return.                 (2) count and uniqueness of array elements               &N Bsp           1 function count () calculates the number of elements in an array or the number of attributes in an object.                           "2" function array_count_values () for statistical arrays The number of occurrences of all values in the                           3 the function Array_unique () function is used to delete duplicates in the array Value and returns a new array that does not have duplicate values                 (3) using the back function to process functions in an array           & nbsp                 1 function array_filter () filters the elements in the array with the back function, returning the new array filtered by the user-defined function.                             2 function Array_walk each element in an array should be Use back function handling   &NBSp                         "3" function Array_map can handle multiple arrays.                 (4) Sorting functions for arrays                 & nbsp           1 simple array sorting: from large to small: bool Rsort (Arry&arry[,int sort_flags]); From small to large: bool Sort (arry&arry[,int sort_flags])                                                      &NBS P     2 sorted by key name array: Ksort () function and Krsort () function                     &NB Sp       3 sorts the array according to the value of the element: Asort () function from small to large sort and arsort () function from large to small sort               & nbsp             4 According to the "Natural sorting" method for sorting the groups                   & nbsp                     General sort: natsort ()     NOTE: Output sorted result array includes case, output not correctly sorted results             & nbsp                           Natcasesort ignoring the case "natural sort": &nbsp ;                           5 "sorted by user-defined set of rules: Usort ();    uasort ();    uksort ()                             "6" Sorting of dimension arrays: Functions Array_multisort ()                   (5) splitting, merging, decomposing and joining arrays    & nbsp                         "1" function array_slice (), take a value out of the array and return.                           2 function Array_splice (), select array But instead of returning them, delete them and replace them with other values.                             "3" function Array_merge (), merges one or more arrays into an array.                           4 function Array_intersect (), meter The intersection of the arithmetic groups.                           5 function Array_diff (), return two arrays Array of difference sets  [three] classes and objects       1: Object instantiation. Format: $ Variable name = new class name ([parameter list]), or $ variable name = new class name; for example: $persion 1 = new persion ();2: The allocation of object type in memory: Stack space segment, simple segment; data segment; code snippet. 3: Access to members of the object: $ Reference name = new class name ([parameter list]);//Object instantiation, for example: $persion 1 = new persion ();$ reference Name, member property = value,//operation to assign a value to a member property, for example: $persio N1->name = "Zhang San";                         ,         &NB Sp               $ reference name-to-member properties                                //Get the value of member properties, for example: Echo persion1->name;                                 ,         &NB Sp       Reference name-to-member method                         & nbsp        //member methods in Access objects, such as: $persion, Method name ();         4: Special object reference "$this"          5: Construction method and destructor method:                    in class declaration Construction method Format:                                Fun Ction__construct ([ReferenceList]) {                                &NB Sp  //Construction method Name is two underscore __construct ();                                       //method body, usually   used for initial assignment of member properties           &NB Sp                            }      &N Bsp               destructor method, PHP will automatically call this method before formation is destroyed:                                  function__destruct () {      &NBS P                            //construction method The name is the one that starts with two underscores __DESTR uct  ();                              &NBSP ;       //method body, usually used to complete some cleanup tasks before objects are destroyed.                          ,         &NB Sp    }           6: Magic Method: __set ();  __get ();  __isset ();  __unset () [Four]PHP Coding tips: How to write PHP programs can improve performance? PHP Optimization for PHP optimization is mainly related to the php.ini in the main parameters of the reasonable adjustment and settings, the following we will look at some of the php.ini in the performance of a large number of parameters should be set.

# Vi/etc/php.ini

(1) PHP function is disabled to find:

Disable_functions =
This option can set which PHP functions are forbidden, there are some functions in PHP the risk is quite large, you can directly execute some system-level script commands, if you allow these functions to execute, when the PHP program vulnerabilities, the loss is very serious! Below we give the recommended disabling function settings:

Disable_functions = Phpinfo,passthru,exec,system,popen,chroot,escapeshellcmd,escapeshellarg,shell_exec,proc_open , Proc_get_status

Note: If your server contains some PHP programs for system State detection, do not disable functions such as Shell_exec,proc_open,proc_get_status.

(2) PHP script execution time found:

Max_execution_time = 30

This option sets the maximum execution time for a PHP program, and if a PHP script is requested and the PHP script does not complete within max_execution_time time, PHP will no longer execute and return a timeout error directly to the client. There is no special need this option to maintain the default setting of 30 seconds, if your PHP script does require a long execution time, you can increase the time setting appropriately.

(3) PHP script handles memory usage found:

Memory_limit = 8M

This option specifies the maximum memory that PHP scripting can occupy, the default is 8MB, and if your server memory is more than 1GB, this option can be set to 12MB for faster PHP script processing efficiency.

(4) PHP global function declaration found:

Register_globals = Off

Many articles on the web about PHP settings are recommended to set this option to on, which is a dangerous setting and is likely to cause serious security problems. If there is no special need, it is highly recommended to keep the default settings!

(5) PHP upload file size limit found:

Upload_max_filesize = 2M

This option sets PHP to allow the maximum upload file size, which defaults to 2MB. Depending on the actual application needs, this setting can be increased appropriately.

(6) Session storage media found:

Session.save_path

If your PHP program uses session dialog, you can set the session storage location to/DEV/SHM,/DEV/SHM is the Linux system unique TMPFS file system, is the memory as the primary storage mode of the file system, better than RAMDisk, Because Diskswap can be used as a supplement, and is the system comes with the function module, do not need to be configured separately. Think of how much faster it will be from disk IO operations to memory operations? Just be aware that the data stored in the/DEV/SHM will be lost after the server restarts. But this is insignificant for the session.

0. It is quicker to use single quotes instead of double quotes to contain strings. Because PHP will search for variables in a string surrounded by double quotes, single quotes will not, note: only echo can do this, it is a string can be used as a parameter of the "function" (in the PHP manual that echo is a language structure, not a real function, so the function with double quotation marks).

PS: In single quotes, PHP does not automatically search for variables, escape characters, and so on, so it is much more efficient. In general, strings are not variable, so using double quotes can result in poor performance.

1, if the method of the class can be defined as static, as far as possible to define as static, it will increase the speed of nearly 4 times times.
PS: In fact, the speed of function, method, static method is not much different. Specifically, "PHP function implementation principle and performance analysis" reproduced "" article.

2. The speed of $row [' ID '] is 7 times times that of $row[id].
PS: Not quite understand, looks like the difference only the latter will first determine whether the ID of the macro exists, if not exist automatically converted to a string.

3. Echo is faster than print, and uses Echo's multiple parameters (referring to commas instead of periods) instead of string connections, such as Echo $str 1, $str 2.

PS: If you use echo $str 1. $STR 2 will require the PHP engine to first connect all the variables, and then in the output, and Echo $str 1, $str the 2,php engine will sequentially output their

4. To determine the maximum number of cycles before executing a for loop, do not calculate the maximum value once per cycle, preferably using foreach instead.
PS: Operations like Count, strlen are actually O (1), so it does not bring too much consumption, of course, it is better to avoid the calculation of each cycle is a good strategy. It is better to use foreach instead for, which is more efficient, and you can use a reference such as foreach ($array as & $var) when considering the consumption of each copy of the foreach ($array as $var).

5. Unregister those unused variables, especially large arrays, in order to free up memory.
Ps:unset ($array) does not immediately release memory, but it is a good practice to release it at any time.

6, try to avoid the use of __get,__set,__autoload.

7, require_once () expensive.
Ps:require_once and include_once need to be weighed, so the efficiency is low, but after the 5.2 version of the efficiency problem has been basically solved.

8, include files as far as possible to use absolute path, because it avoids PHP to include_path to find the speed of the file, parsing the operating system path takes less time.
PS: Support, try to use less iniset () to set include_path.

9. If you want to know when the script starts executing (that is, the server side receives the client request), use $_server[' request_time '] better than time ().
ps:$_server[' Request_time ' saves the timestamp at the time the request was initiated, and time () returns the Unix timestamp at the current moment.

10, function instead of regular expression to complete the same function.
PS: This function refers to Strtok, Strstr, Strpos, Str_replace, substr, explode, implode, and so on.

11, the Str_replace function is faster than the Preg_replace function, but the efficiency of the STRTR function is four times times the Str_replace function.
PS: String operations are faster than regular replacements.

12, if a string substitution function, can accept an array or character as a parameter, and the parameter length is not too long, then you can consider an extra piece of replacement code, so that each pass argument is a character, rather than write a line of code to accept the array as the query and replace parameters.
PS: You need to take into account the overhead differences between built-in functions and user-defined functions, I'm afraid this is not worth the candle.

13. Use the Select Branch statement (that is, switch case) better than using multiple if,else if statements.
ps:php switch supports numeric and string variables, which is better than switch C, and is recommended for use.

14. Masking error messages with @ is extremely inefficient and extremely inefficient.

15, open the Apache mod_deflate module, can improve the browsing speed of the page.

16, the database connection should be turned off when used, do not use long connection.
PS: Before connecting, it is best to set the appropriate timeout mechanism, such as link timeout, read/write timeout, wait timeout, etc.

18, increment the local variable in the method, the speed is the quickest. is almost equivalent to the speed at which local variables are called in the function.

19, incrementing a global variable is twice times slower than incrementing a local variable.

20, incrementing an object property (such as: $this->prop++) is 3 times times slower than incrementing a local variable.

21. Incrementing an undefined local variable is 9 to 10 times times slower than incrementing a pre-defined local variable.

22. Defining only a local variable without calling it in the function also slows down the speed (which is equivalent to incrementing a local variable). PHP will probably check to see if there are global variables.

23. The method invocation appears to be independent of the number of methods defined in the class, because I added 10 methods before and after the test method, but there was no performance change.

24. A method in a derived class runs faster than the same method defined in the base class.

25. Call an empty function with one parameter, which takes the same amount of time as performing a local variable increment operation of 7 to 8 times. A similar method call takes a time close to 15 local variable increment operations.

26, Apache parsing a PHP script time is 2 to 10 times times slower than parsing a static HTML page. Use static HTML pages as much as possible and use fewer scripts.

27. Unless the script can be cached, it will be recompiled every time it is called. Introducing a set of PHP caching mechanisms can typically improve performance by 25% to 100% to eliminate compilation overhead.

28, try to do the cache, you can use memcached. The memcached is a high-performance memory object caching system that can be used to accelerate dynamic Web applications and reduce database load. Caching of the OP code is useful so that the script does not have to recompile for each request.

29. When you manipulate a string and need to verify that its length satisfies a certain requirement, you will of course use the strlen () function. This function executes quite quickly because it does not do any calculations and only returns the length of the known string stored in the Zval structure (the built-in data structure of C for storing PHP variables). However, because strlen () is a function, it is somewhat slower, because function calls go through a number of steps, such as lowercase letters (lowercase, PHP does not differentiate between function names), and hash lookups, which follow the called functions. In some cases, you can use the isset () technique to speed up execution of your code.

(Example below)

if (strlen ($foo) < 5) {echo "Foo is too Short" $$}

(compare with the following tips)

if (!isset ($foo {5})) {echo "Foo is too Short" $$}

Calling Isset () happens to be faster than strlen (), because unlike the latter, Isset (), as a language structure, means that its execution does not require function lookups and lowercase letters. In other words, you're actually not spending much overhead in the top-level code that examines the length of the string.

30. When the increment or decrement of the variable $i is executed, $i + + will be slower $i than + +. This difference is unique to PHP and does not apply to other languages, so please do not modify your C or Java code and expect them to become fast and useless. + + $i is faster because it requires only 3 instructions (opcodes), $i + + requires 4 instructions. The post increment actually produces a temporary variable, which is then incremented. The predecessor increment is incremented directly on the original value. This is one of the most optimized processing, as Zend's PHP optimizer did. It is a good idea to keep this optimization in mind, as not all of the instruction optimizer will do the same optimizations, and there are a large number of Internet service providers (ISPs) and servers that do not have the command optimizer installed.

31, not the object-oriented (OOP), object-oriented tends to be very expensive, each method and object calls will consume a lot of memory.

32, not to use the class to implement all the data structure, arrays are also useful.

33, do not subdivide the method too much, think carefully about what you really want to reuse what code?

34, when you need, you can always break down the code into methods.
PS: Decomposition into a method to be appropriate, less frequent use of the method as far as possible to write code directly, you can reduce the function stack overhead, and method nesting should not be too deep, otherwise greatly affect the efficiency of PHP operation.

35, try to use a large number of PHP built-in functions.

36. If there are a lot of time-consuming functions in your code, you might consider implementing them in C extensions.

37. Evaluate the test (profile) of your code. The inspector will tell you what parts of the code are consuming time. The Xdebug debugger contains an inspection program that can show the bottleneck of the code in general.

38, Mod_zip can be used as Apache module, to compress your data instantly, and to reduce the data transfer volume by 80%.

39, in the case can be replaced with file_get_contents file, fopen, feof, Fgets and other series of methods, as far as possible with the file_get_contents, because his efficiency is much higher! But pay attention to file_get_ Contents PHP version problem when opening a URL file;
PS: This to remember, try to use file_get_contents and file_put_contents, do not need to determine whether the file handle opened successfully.

40, as far as possible to file operations, although PHP file operation efficiency is not low;

41, optimize the Select SQL statement, as far as possible, as little as possible to insert, update operation (on the update, I was a bad batch);

42, as far as possible the use of PHP internal functions (but I have to find a php non-existent function, wasted can write a custom function of time, experience problem ah!);
PS: Built-in functions are nearly an order of magnitude more efficient than user-defined functions.

43, the loop inside do not declare variables, especially large variables: objects (this does not seem to be the only thing in PHP to pay attention to it?);
PS: This is necessary, too many variables or too large, the cost of each redistribution cannot be ignored.

44, multidimensional arrays try not to loop nested assignment;

45, in the case of PHP internal string manipulation function, do not use regular expressions;

46, foreach more efficient, try to use foreach instead of while and for loop;

47. Use single quotation marks instead of double quotation marks to reference strings;

48, "Replace I=i+1 with I+=1." In line with C + + habits, efficiency is high ";

49, to global variables, should be used up on unset () off;

[V] Interface conversioninclude ("Path to the interface you want to switch to");require("The path of the interface to which you want to switch");require_once("Path to the interface to be converted to"); require more rigorous than include [L VI] Understanding synchronous and asynchronous synchronization means that after the sender sends out the data, the receiving party sends back the response before sending the next packet.

Asynchronous means that after the sender sends out the data, the receiver sends back the response, and then the next packet is communicated.

GET-Requests data from the specified resource.
POST-Two ways to add a data button to be processed to a specified resource: <input type= "button" value= "value" > or <button> value </button><form action = "Commit path" method= "Submission Method" >url: Where to send form data The method property specifies how the form data is sent (the form data is sent to the page specified by the Action property), and the form data can be used as a URL variable (method= "get") or HTTP Post (method= "POST") is sent in the same way. Two ways to send data to the server using HTTP--post and GET, the main difference is how the data is sent to the server: GET appends the form domain name and value to the end of the URL as a key/value pair. PHP can read this information from an associative array $_get[], an associative array that is sent to the server when the form is submitted. The URL? The data that follows is visible. POST also sends data through an associative array, but is encoded differently, and the array in the URL is not visible to the end user. $_post[] Associative array contains all the information obtained by the form element. Similar to the $_get[] array, which is also a series of name/value pairs consisting of the form element name and value.

Small PHP Records

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.