Article directory
- Code reuse and function writing
- Benefits of code reuse
- Use the require() function and the include() function
- require() function -- introduce code
- require() function -- making web site template
- Use auto prepend file and auto append file
- Using PHP functions
- Custom function
- Basic structure of function
- Parameter usage
- Understanding scope
- Reference passing and value passing
- Keyword return
- Recursive implementation
Code reuse and function writing
Benefits of code reuse
Purpose: reduce costs, increase reliability and improve consistency
cost
The cost of using existing software is usually less than the cost of developing an equivalent product;
The cost of buying software products is less than the cost of using open source projects (modifying existing code is more difficult than writing new code).
reliability
There are two situations that are easy to be ignored when rewriting code: one is some functional code added by the original author; the other is new code added to the source code after the test finds defects.
=>Using existing mature code is usually more reliable than new "green" code
Legacy code (code modules too old): develop alternative libraries for organizational use
Uniformity
The external interface provided by the system should be consistent: write a piece of new code that can be consistent with other parts of the system function.
Use the require() function and the include() function
1. Function: load files in PHP script. In general, this file can contain anything you want to introduce into a script, including PHP statements, text, HTML tags, PHP functions, or PHP classes.
They are almost the same, the only difference is that after the statement fails to execute, require() will give a fatal error, and include() will only give a warning.
2. The corresponding variant functions are require once() and include once(). It is used to ensure that an imported file can only be imported once, so as to prevent the introduction of the same function library twice by mistake and the error of defining functions repeatedly. Moreover, the variant function runs faster than the original function.
require() function - introduce code
#reusable.php <?php echo "Here is a very simple PHP statement.<br />"; ?>
#main.php <?php echo "This is the main file.<br />"; require('reusable.php'); #Will be replaced and executed by the requested file content echo "The script will end now.<br />"; ?>
Key points of the require() function: pay attention to the different ways to handle file extensions and PHP Tags -PHP does not check the extension of the required file. This means that as long as you don't want to call the file directly, you can name the file in any way. For example, when you name the reusable.php file with. HTML, the PHP tags in it will be treated as text or HTML and will not be executed. -When the file is loaded using the require() statement, it is executed as part of the PHP file. -If files with. inc or other non-standard extensions are saved in the Web document tree, and users load them directly in the browser, users will be able to view the source code in plain text, including any passwords. Therefore, it is important to keep the file outside the Web document tree or use a standard file extension.
require() function - make web site template
<!-- home.html --> <!DOCTYPE html> <html> <head> <title>TLA Consulting Pty Ltd</title> <link href="styles.css" type="text/css" rel="stylesheet"> </head> <body> <!-- page header --> <header> <img src="logo.gif" alt="TLA logo" height="70" width="70" /> <h1>TLA Consulting</h1> </header> <!-- menu --> <nav> <div class="menuitem"> <a href="home.html"> <img src="s-logo.gif" alt="" height="20" width="20" /> <span class="menutext">Home</span> </a> </div> <div class="menuitem"> <a href="contact.html"> <img src="s-logo.gif" alt="" height="20" width="20" /> <span class="menutext">Contact</span> </a> </div> <div class="menuitem"> <a href="services.html"> <img src="s-logo.gif" alt="" height="20" width="20" /> <span class="menutext">Services</span> </a> </div> <div class="menuitem"> <a href="about.html"> <img src="s-logo.gif" alt="" height="20" width="20" /> <span class="menutext">About</span> </a> </div> </nav> <!-- page content --> <section> <h2>Welcome to the home of TLA Consulting.</h2> <p>Please take some time to get to know us.</p> <p>We specialize in serving your business needs and hope to hear from you soon.</p> </section> <!-- page footer --> <footer> <p>© TLA Consulting Pty Ltd.<br /> Please see our <a href="legal.php">legal information page</a>.</p> </footer> </body> </html>
You can usually split this file and name these parts header. PHP, home.php, and footer. PHP, respectively. Both header.php and footer.php contain code that can be reused in other pages.
<!-- home.php --> <?php require('header.php'); ?><?php require('header.php'); ?> <!-- page content --> <section> <h2>Welcome to the home of TLA Consulting.</h2> <p>Please take some time to get to know us.</p> <p>We specialize in serving your bussiness needs and hope to hear from your soon.</p> </section> <?php require('footer.php'); ?>
Be careful! When a file is called through require (), the file name does not affect how they are handled.
Recommended strategy: save the. inc file in the central European crown of a directory that can be accessed by scripts, but the imported file will not be loaded by the web server, that is, saved outside the web document tree.
The file header.php contains the CSS definitions used by the page and a table showing the company name and navigation menu.
<!-- header,php --> <!DOCTYPE html> <html> <head> <title>TLA Consulting Pty Ltd</title> <link href="styles.css" type="text/css" rel="stylesheet"> </head> <body> <!-- page header --> <header> <img src="logo.gif" alt="TLA logo" height="70" width="70" /> <h1>TLA Consulting</h1> </header> <!-- menu --> <nav> <div class="menuitem"> <a href="home.html"> <img src="s-logo.gif" alt="" height="20" width="20" /> <span class="menutext">Home</span> </a> </div> <div class="menuitem"> <a href="contact.html"> <img src="s-logo.gif" alt="" height="20" width="20" /> <span class="menutext">Contact</span> </a> </div> <div class="menuitem"> <a href="services.html"> <img src="s-logo.gif" alt="" height="20" width="20" /> <span class="menutext">Services</span> </a> </div> <div class="menuitem"> <a href="about.html"> <img src="s-logo.gif" alt="" height="20" width="20" /> <span class="menutext">About</span> </a> </div> </nav>
The file footer.php contains tables that display footnotes at the bottom of each page.
<!-- footer.php --> <!-- page footer --> <footer> <p>© TLA Consulting Pty Ltd.<br /> Please see our <a href="legal.php">legal information page</a>.</p> </footer> </body> </html>
If you want to ensure that a file will be treated as plain text or HTML, and no PHP script will be executed, you can use readfile() as an alternative. This function will echo the contents of the file without parsing it.
Use auto prepend file and auto append file
The php.ini configuration file provides two configuration items: Auto file and auto append file. By pointing these two options to header and footer files, you can ensure that they load before or after each page. If the file does not exist, a warning is generated.
#windows Platform: auto_prepend_file = 'c:/path/to/header.php' auto_append_file = 'c:/path/to/footer.php' #UNIX platform auto_prepend_file = '/path/to/header.php' auto_append_file = '/path/to/footer.php'
If you use these instructions, you don't need to enter the include () statement, but headers and footnotes are no longer optional parts of the page.
If you are using an Apache Web server, you can set and change different configuration options for a single directory. To complete the setup change, the server must be set to allow its master profile to be overwritten. To set up auto pre join and auto append for a directory, you need to create a file named. htaccess in that directory.
.htaccess Document code: php_value auto_prepend_file "/path/to/header.php" php_value auto_append_file "/path/to/footer.php" - No equal sign - Great flexibility to run on a shared machine that only affects your directory - Disadvantage: every read and parsed file in the directory needs to be processed every time, rather than once at startup, so the performance will be reduced
Using PHP functions
Function: contains code that can perform a single designed task and can be reused.
Function is a self-contained module that gives the calling interface. It can perform some tasks and return results (optional).
Calling function
phpinfo() function: shows the installed PHP version, PHP information, Web server settings, and a large number of different PHP and server variable values.
Through the function prototype to understand the number of parameters required by the function, the object represented by each parameter and the data type of each parameter.
Function parameters are included in parentheses. You can assign or ignore optional parameters. If you ignore them, the function will use the default value. A function with multiple optional parameters must use the default values from right to left.
call to undefined function
The following error is displayed when calling an undefined function:
Error message of PHP function: it can tell us which line of the file the error appears in, and the name of the function to be called. -Is the function name spelled correctly? -Does this function exist in the PHP version used? -Does the function belong to an extension library that is not installed or enabled? -Is the file containing the function imported? -Is the function scope correct?
One disadvantage of PHP is that the function naming rules are not uniform. The reason for the inconsistency is that PHP functions are implemented based on C function library.
Understand case and function name
Function calls are not case sensitive!!! But try to be consistent and use the same case policy.
Function names and variable names are different, and variable names are case sensitive.
Custom function
Declaring a function allows us to use our own code like built-in functions.
Built in functions allow you to interact with files, use databases, create drawings, and link to other servers.
Basic structure of function
A function declaration will create or declare a new hanshu.shengming starting with the keyword function, providing the function name and necessary parameters, and then giving the code to be executed each time the function is called.
Custom functions can only be used in scripts that declare them. The frequently used functions are included in a file, and then the require() statement can be used in all scripts, so it can be used in other scripts.
In a function, curly braces include the code to complete the required tasks. In curly braces, you can include any code that is legal elsewhere in your PHP script, including function calls, new variable or function declarations, require() or include() statements, class declarations, and HTML scripts.
Function naming
Function names must be concise and descriptive.
Restrictions on function naming: -The function name cannot be the same as the existing function name; -Function name can only contain letters, numbers and underscores; -Function name cannot start with a number. A custom function cannot have the same name as a built-in function or a user-defined function. Although it is possible to reuse a function name in different files, this conference has been confusing for years and should be avoided.
Parameter usage
<!-- create_table.php --> <?php #Create function function create_table($data) { echo '<table>'; reset($data); $value = current($data); while ($value) { echo "<tr><td>$value</td></tr>\n"; $value = next($data); } echo '</table>'; } #Calling function $my_data = ['First piece of data','Second piece of data','And the third']; create_table($my_data); ?>
Passing parameters allows us to get the data generated outside the function.
<!-- create_table_2.php --> <?php #Create function 2 function create_table($data, $header=NULL, $caption=NULL) { echo '<table>'; if ($caption) { echo "<caption>$caption</caption>"; } if ($header) { echo "<tr><th>$header</th></tr>"; } reset($data); $value = current($data); while ($value) { echo "<tr><td>$value</td></tr>\n"; $value = next($data); } echo '</table>'; } #Calling function $my_data = ['First piece of data','Second piece of data','And the third']; $my_header = 'Data'; $my_caption = 'Data about something'; create_table($my_data, $my_header, $my_caption); ?>
Why are parameters optional?? Because default values have been defined for them in the function.
Optional parameter values need not be given in full; some can be given and some ignored. The parameters are assigned from left to right.
be careful!!! Optional parameter values cannot be given in an interval when called.
Understand the number of parameters passed and their values -Func? Num? Args() returns the number of parameters passed in -Func get args() returns an array of parameters -Func get arg() accesses parameters one by one
Understanding scope
The variable scope controls where variables are visible and available in the code. -The scope of variables declared within a function starts from the statement in which they are declared to the end of the function. This is called the function scope. These variables become local variables. -Variables declared outside a function are scoped from the statement in which they are declared to the end of the file, not inside the function. This is called the global scope. These variables are called global variables. -Super global variable, which is visible inside and outside the function. -Using require() and include() does not affect the scope. If these two statements are used inside a function, the function scope is applicable. If they are not, the global scope is applicable. -The keyword global can be used to specify that a variable defined or used in a function has a global scope. -You can manually delete variables by calling unset ($variable ﹐ name). If the variable is deleted, it is not in the scope specified by the function.
function fn(){ $var = "contents"; # Variable $var is a local variable with function scope } fn(); echo $var; #Variable $var is a global variable with global scope
<?php function fn(){ echo 'inside the function, at first $var = '.$var.'<br />'; $var = 2; echo 'then, inside the function,$var = '.$var.'<br />'; } $var = 1; fn(); #Functions are not executed until they are called echo 'outside the function,$var = '.$var.'<br />'; ?>
The variables created inside the function have global scope (after the function call, the variables also exist outside the function) < = keyword Global
<?php function fn(){ global $var; $var = "contents"; echo 'then, inside the function,$var = '.$var.'<br />'; } fn(); echo 'outside the function,$var = '.$var.'<br />'; ?>
Reference passing and value passing
<?php function incremnet($value, $amount = 1){ $value = $value + $amount; } $value = 10; incremnet($value); echo $value; ?>
$value is a different variable. The internal variable is in the function scope, with a value of 11. The external variable is in the global scope, with a value of 10
The normal way to call function parameters is to pass values. When a parameter is passed, a new variable containing the passed in value is created. It's a copy of the original variable. You can modify it in any way, but the original variable value outside the function will not be changed. If you need to modify the value of the incoming variable, use pass by reference. At this point, when the parameter is passed to the function. Instead of creating a new variable, the function gets a reference to the original variable. This reference has a variable name that starts with $, and can be used like any other variable. The difference is that it does not get the original value of the variable, but points to the original value. Any changes to the reference affect the original variable value. -By adding a & before the parameter name defined by the function, you can specify the parameter to be passed by reference.
<?php function incremnet(&$value, $amount = 1){ $value = $value + $amount; } $a = 10; echo $a.'<br />'; incremnet($a); echo $a.'<br />'; ?>
Keyword return
The keyword return will terminate the execution of the function.
<?php function test_return(){ echo "This statement will be executed."; return; echo "This statement will never be executed."; } test_return(); ?>
The error condition is a common reason to use the return statement to terminate the function execution to the end.
<?php function larger($x, $y){ if ((!isset($x)) || (!isset($y))){ #isset() built-in function to confirm whether the variable has been created and assigned echo "This function requires two numbers."; return; } if ($x >= $y){ echo $x.'<br />'; }else{ echo $y.'<br />'; } } $a = 1; $b = 2.5; $c = 1.9; larger($a, $b); larger($c, $a); larger($d, $a); ?>
Returns a value from a function. A function that normally performs a specific task but does not return a specific value will return true or false to indicate whether the function was executed successfully.
<?php function larger($x, $y){ if ((!isset($x)) || (!isset($y))){ #isset() built-in function to confirm whether the variable has been created and assigned return false; } if ($x >= $y){ return $x; }else{ return $y; } } $a = 1; $b = 2.5; $c = 1.9; $d = NULL; echo larger($a, $b).'<br />'; echo larger($c, $a).'<br />'; echo larger($d, $a).'<br />'; ?>
Recursive implementation
A recursive function is a function call function itself. These functions are especially suitable for browsing dynamic data structures. Recursive functions will create several copies of themselves in memory, and will incur the cost of multiple function calls.
In many cases, recursion can be used instead of loops. But recursion is slower than loops and takes up more memory.
# recursion.php <?php # Print the contents of the string in reverse order function reverse_r($str){ #recursion if(strlen($str) > 0){ reverse_r(substr($str, 1)); } echo substr($str, 0, 1); return; } function reverse_i($str){ #loop for($i = 1; $i <= strlen($str); $i ++){ echo substr($str, -$i, 1); } return; } reverse_r('Hello'); echo '<br />'; reverse_i('Hello'); ?>
Anonymous (closure) function
Anonymous (closure) function: usually a function without a name.. They are usually used in callback function scenarios. That is, functions passed to other functions.
You can declare functions as anonymous functions inline, or you can use variables to hold closure functions.
A closure function has access to global scope variables, but they must be defined in the closure function definition using the use keyword display.
#closures.php <?php $printer = function($value){echo "$value <br />";}; #Using variables to save closure functions $products = [ 'Tires' => 100, 'Oil' => 10, 'Spark Plugs' => 4 ]; $markup = 0.20; $apply = function(&$val) use ($markup){ #Specifies that the $markup variable with global scope should be available in anonymous functions $val = $val * (1 + $markup); }; array_walk($products, $apply); array_walk($products, $printer); ?>