PHP Study Notes 5: code reuse and functions

Source: Internet
Author: User
PHP Study Notes 5: code reuse and function reading notes in PHP and MySQL Web Development:


1. Benefits of code reuse

Cost, reliability, consistency

Note: as long as the original code is modular and well written, repeated use of the code will save a lot of work. During work, you can try to identify the code segment that may be called again in the future.


2. require () and included code execution problems

If you want a PHP code in an included file to be processed as a PH code, you must place the PHP code between PHP tags (no matter what suffix the file containing the code is, jpg and rar suffixes do not matter, as long as the php code inside is put in the php label, can be executed after being included)

However, the file suffix will affect whether the browser directly loads the file when accessing it, and view the source code in the form of common text.

Therefore, to ensure security, save the included files outside the document tree or use the standard file extension.

Example:


3. if the contained file does not exist, require will give a fatal error, while include will only give a warning.

There are also two variants, require_once () and include_once (), to ensure that an included file can only be introduced once.

Note: When the function library is introduced, these two functions are very useful. using these two functions can prevent the wrong introduction of the same function library twice, resulting in repeated definition errors. If you are concerned about coding practices, you can consider using require () and include () because they run faster.





When external files are called Through require (), the file name does not affect their processing.


4. even if a file with a php suffix is directly accessed by writing HTML code, it is still parsed as html.

Note: to ensure that a file is treated as plain text or HTML without executing any PHP code, you can use readfile () as an alternative. This function will echo the file content and will not parse it. If the text provided by the user is used, this may be an important security issue.


5. a good static page template

Example:



...


...


....


...



6. add the header and footer to each page.

1) configure php. ini

Auto_prepend_file

Auto_append_file

Windows example:

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"

UNIX example:

Auto_prepend_file = "/home/username/include/header. php"

Auto_append_file = "/home/username/include/footer. php"

Note: If you use these commands, you do not need to enter the include () statement, but the header and footer are no longer the optional content of the page.

2) configure. htaccess for each directory in Apache Web

This file must contain the following two lines of code:

Php_value auto_prepend_file = "/home/username/include/header. php"

Php_value auto_append_file = "/home/username/include/footer. php"

Note: The syntax is different from that in php. ini. there is no equal sign, but many settings in php. ini can be modified in this way.

Note: setting options in. htaccess provides great flexibility. It can be performed on a shared host that only affects your Directory. you do not need to restart the server or the administrator.

The disadvantage is that each file read and parsed in the directory using. htaccess must be processed every time, instead of only once when it is enabled.


7. question about optional parameters in the function

Note that function names in PHP are case-insensitive and variable names are differentiated, while JavaScript is case-insensitive.


For example, a function prototype:

Resource fopen (string filename, string mode [, bool use_include_path [, resource content])

Explanation:

"Resource" tells us that this function will return a resource. in the fopen () function, the function prototype provides four parameters. [] Brackets indicate that this parameter is optional. you can ignore them. if you ignore them, they use the default value only.

Note: a function with multiple optional values must be assigned a value from left to right. For example, you may not provide the content parameter, or use_include_path and content parameters, but you cannot provide use_include_path, but only the content parameter.

Test:

Example 2: note that php only transmits values.

16 is assigned to 3rd parameters c in turn.



8. call undefined functions


Fatal error: Call to undefined function tests1 () in D: \ wamp \ www \ study \ fuc. php on line 10

Note: The error message provided by PHP is usually very useful. it tells us the file in which the error occurs, which line, and the name of the function we call.

If you see this information, there are three possibilities:

1) whether the function name is correctly spelled;

2) Does this function exist in all PHP versions;

3) whether the called function is part of the PHP extension, and this part is not loaded.


9. basic function structure

1) function naming has the following restrictions:

Function names cannot be duplicated with existing functions (function names can be reused in many languages, such as "overload". function overloading is not supported in PHP );

The function name can only contain letters, numbers, and underscores and cannot start with a number.


Note:

$ Name is not a valid name of a function, but can be correctly executed for function calls similar to $ name (); determined by the value of $ name. PHP can retrieve the value stored in $ name, find a function with that name, and call this function. This type of function is called a variable function and sometimes useful.


2) in braces {}, code that can be included in other parts of the PHP script is legal, including function calls, new variables or function declarations, require () or include () statement class declaration and HTML code.

If you want to exit PHP in a function and input an HTML script, you can use a popular PHP tag as you do elsewhere in the script, and then write HTML. Example:

Function my_function (){

?>

My function was called

}

?>


10. Three helper functions to determine the passed parameters

Func_num_args (): returns the number of input parameters.

Func_get_arg (): obtains a parameter at a time.

Func_get_args (): array of returned parameters



11. understand scope

1) the local variables in the function and the global variables outside the function can have the same name and no conflict.

2) there is a so-called "super global variable"

3) you can manually specify that the variables in the function have a global scope.

4) you can manually delete a variable by calling unset ($ variable_name). If the variable is deleted, it is no longer in the scope specified by the parameter.

Example:

Because $ var is not assigned a value.

Suggestion: Avoid using the same variable name inside and outside the function.


12. parameter reference transfer and value transfer

Value transfer:

Function increment ($ value, $ amount = 1)

{...}

Reference transfer:

Function increment (& $ value, $ amount = 1)

{...}

The original value can be changed.


13. return

When the execution of a function ends, it is either because all commands are executed, or "return" is used. return can be left blank, but it is recommended to return.


14. recursion

PHP supports recursive functions. recursive functions are called by functions themselves. These functions are especially suitable for browsing dynamic data structures, such as connection lists and trees.

However, almost no Web-based applications require such a responsible data structure. In many cases, recursion can be used to replace loops, because both of them are repetitive. Recursive functions are slower than loops and occupy more memory. Therefore, use as many loops as possible.


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'
';

Reverse_ I ('Hello ');


?>


However, as shown in the preceding example, the recursive section generates a new copy of the function code in the memory of the server every time this function is called, recursive functions create several replicas in the memory, and overhead of multiple function calls is generated.

Although recursion looks more beautiful, it is necessary to give a termination condition. Otherwise, the server memory will be exhausted or the maximum number of calls will be reached.


15. namespace)

Generally, a namespace is an abstract container that can contain a group of identifiers;

In PHP, the namespace can contain the functions, constants, and classes you define.

From the perspective of structure, defining namespaces for user-defined functions and classes is somewhat like:

1) all functions, classes, and constants in a namespace are prefixed with namespaces.

2) non-full-path class, function, and constant names will be parsed at runtime. before you view the global space, you will first view the namespace.

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.