PHP Learning Note 5: Code Reuse and functions

Source: Internet
Author: User
Tags function prototype php and mysql

Read the collection of PHP and MySQL Web development notes:

http://my.oschina.net/bluefly/blog/478580


1. Benefits of code reuseCost, reliability, consistency note: Reusing code can save a lot of effort as long as the original code is modular and well written. At work, try to identify the code snippets that might be called again in the future.
2. require () is executed with the included codeProblem if you want the PHP code in a contained file to be processed as a ph code, you must put the PHP code between the PHP tags (regardless of the file containing the code suffix, jpg, rar suffix does not matter, as long as the inside PHP code is placed in the PHP tag, Can be executed after it is included) but the file suffix will affect whether the browser accesses the file directly or not, and views the source code as plain text. Sofor security, save the included file outside of the document tree, or use a standard file name extension

Example:


3. If If the included file does not exist, require will give a fatal error, and the include will only give a warning。 There are also two variants,require_once (), include_once ()Ensure that a contained file can only be introduced once. Note: These two functions are useful when the library is introduced, using these two functions to prevent errors from being introduced into the same library two times, resulting in duplicate-defined errors. If you care about coding practices, consider using require () and include (), as they run faster.



When external files are called through require (), the names of the files do not affect their handling

4, even if the php suffix, file, if you write HTML code, direct access, or as HTML is parsedProcessed by

Note:if want to ensure that a file is treated as plain text or HTML and will not execute any PHP , you can use ReadFile () as an alternative method。 This function echoes the contents of the file and does not parse it. If you are using user-supplied text, this can be an important security issue.
5, a good static page templateExample: <body> <!--page Header--... <!--menu--
... <!--page content-->
.... <!--page footer-->
... </body>
6. Want to add headers and footnotes to each page1) configuration php.iniAuto_prepend_file Auto_append_file Windows examples are as follows: Auto_prepend_file = "C:/Program Files/apache software froundation/apache2.2/include/header.php"
Auto_append_file = "C:/Program files/apache froup/apache2/include/footer.php"
The UNIX example is as follows: Auto_prepend_file = "/home/username/include/header.php"
Auto_append_file = "/home/username/include/footer.php"Note: If you use these instructions, you do not need to enter the include () statement, but the header and footer are no longer the optional contents of the page in the page 2) under the Apache Web, each directoryConfiguration . htaccessThis file needs to contain the following two lines of code: Php_valueAuto_prepend_file = "/home/username/include/header.php"
Php_value Auto_append_file = "/home/username/include/footer.php"Note: Its syntax differs from php.ini, there is no equal sign, but many php.ini settings can be modified in this way. Note: There is great flexibility in setting options in. htaccess. It can be done on a shared host that affects only your directory, without restarting the server or requiring the administrator to do it all. The disadvantage is that every file that is read and parsed in the. htaccess directory is processed every time, rather than only once when it is enabled.
7. Problems with optional parameters in the function first notice that the function names in PHP are not case-sensitive, variable names are differentiated, and JavaScript is differentiated.
For example, a function prototype: Resource fopen (string filename, string Mode[, BOOL Use_include_path[, Resource content]]) explains in detail: "Resource" tells us that the function returns a resource, in the fopen () function, the function prototype gives 4 parameters. [] The parentheses indicate that this parameter is optional and can be ignored, and if they are omitted, they will use the default only.Note: A function with more than one optional value must be assigned to the optional parameter from left to right。 For example, you can not give a content parameter, or you can not provide use_include_path and content parameters, but you cannot provide use_include_path, but only the content parameter.

Test:

Example 2: Notice ha, another argument is that PHP only passes values.

16 assigns the 3rd parameter C in turn.

8. Calling undefined functions
Fatal error:call to undefined function tests1 () inch D:\wamp\www\study\fuc.php on line 10Note: Usually the error message given by PHP is very useful, and it tells us which file, which line, and the name of the function we are calling. If you see this information, there are 3 possible: 1) The spelling of the function name is correct, 2) whether the function exists in all PHP versions, and 3) whether the function being called is part of the PHP extension, and the part is not loaded.
9. Basic structure of function1) function naming has the following restrictions function names can not drink the name of the existing function (many languages allow repeated use of the function name, called "overloaded", PHP does not support function overloading); Function names can only contain letters, numbers, and underscores and cannot start with a number.
Attention:$name is not a valid name for a function, but is similar to a function call of $name (), which can also be executed correctly , which is determined by the value of the $name.。 PHP can remove the value stored in $name, look for a function with that name, and call the function. This type of function is called variable Functions, and sometimes it's useful.
2) in {} curly braces, you can include code that is valid elsewhere in the PHP script, including function calls, new variables or function declarations, require () or include () statement class declarations, and HTML code. If you want to quit PHP in a function and enter an HTML script, you can use a wind PHP tag, and then write the HTML, as you did elsewhere in the script. Example: <?php function My_function () { ?>My function was called

<?php  } ?>
10. 3 helper functions to determine the parameters passed inFunc_num_args (): Returns the number of arguments passed in Func_get_arg (): Get one parameter at a time Func_get_args (): Returns an array of arguments

11. Understanding the Scope1) within the function of local variables and functions outside the global variables, can be the same variable name, do not conflict, understand. 2) There are so-called "Super Global Variables" 3) Global can manually specify that the variables in the function have global scope. 4) Call unset ($variable _name) to delete the variable manually, and if the variable is deleted, it is no longer in the scope specified by the parameter.

Example:

Because $var is not assigned to a value. Recommendation: Avoid using the same variable name inside and outside the function.


12. Reference passing and value passing of parameters Value passing: function Increment ( $value, $amount = 1) {...}Reference Delivery: function Increment ( & $value, $amount = 1) {...} reference pass, can change the original value.
13. ReturnWhen the execution of a function ends, either because all commands have been executed, or "return" is used, return does not return a value, but it is recommended to return.
14. RecursionPHP supports recursive functions, and recursive functions are functions that call themselves. These functions are especially useful for navigating dynamic data structures, such as connection lists and trees. However, almost no web-based application requires the use of such a responsible data structure. In many cases, recursion can be used to replace loops, because both do things repeatedly. Recursive functions are slower than loops and occupy more memory, so you should use as many loops as possible.
<?php
function Reverse_r ($STR) {if (strlen ($STR) >0) Reverse_r (substr ($STR, 1));    Echo substr ($str, 0, 1); Return }
function Reverse_i ($STR) {for ($i =1; $i <=strlen ($STR); $i + +) {echo substr ($str,-$i, 1); } return; }
Reverse_r (' Hello '); echo ' <br/> '; Reverse_i (' Hello ');
?>
However, as shown in the example above, recursively, each call to this function generates a new copy of the function code in the server's memory, and the recursive function creates several copies of itself in memory, and will incur the overhead of multiple function calls. Although recursion looks more beautiful, it is important to give the termination condition, otherwise it will cause the server to run out of memory or reach the maximum number of calls.
15. Namespaces (also called namespace, namespace)Typically, a namespace is an abstract container that can contain a set of identifiers; in PHP, namespaces can contain functions, constants, and classes that you define. From a structural point of view, a bit of defining a namespace for custom functions and classes: 1) All functions, classes, and constants in a namespace are prefixed with a namespace prefix. 2) Non-full path classes, functions, and constant names are resolved at run time, and the namespace is first viewed before the global space is viewed.


PHP Learning Note 5: Code Reuse and functions

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.