Home > Backend Development > PHP Tutorial > Core technologies for PHP and Mysql web application development Part 1 Php basics-3 Code organization and reuse 2_PHP tutorial

Core technologies for PHP and Mysql web application development Part 1 Php basics-3 Code organization and reuse 2_PHP tutorial

WBOY
Release: 2016-07-21 15:26:31
Original
867 people have browsed it

From this chapter, we learned about

. Creating functions that can be called to reuse code

. Passing parameters to functions and returning values ​​from functions and interacting with variables and data in different parts of the script.

. Store code and function groups in other files, and include these files in our scripts.

3.1 Basic code reuse: Functions

3.1.1 Definition And calling the function

The keyword function informs PHP that this is a function, followed by the name of the function, which can be letters, numbers, characters or underscores

Followed by the function name is the parameter list, Then there is the function body. For functions with the same name but different parameter lists in other languages, PHP does not support this feature.

Copy code The code is as follows:

function booo_spooky()
{
echo "I am booo_spooky. This name is okay!
n";
}
function ____333434343434334343()
{
echo <<I am ____333434343434334343. This is an awfully
unreadable function name. But it is valid.
DONE;
}
//
// This next function name generates:
//
// Parse error: syntax error, unexpected T_LNUMBER,
// expecting T_STRING in
// /home/httpd/www/phpwebapps/src/chapter03/playing.php
// on line 55
//
// Function names cannot start with numbers
//
function 234letters()
{
echo "I am not valid
n";
}
//
// Extended characters are ok.
//
function grüß_dich()
{
echo "Extended Characters are ok, but be careful!< br/>n";
}
//
// REALLY extended characters are ok too!! Your file will
// probably have to be saved in a Unicode format though,
// such as UTF-8 (See Chapter 5).
//
function 日本语のファンクション()
{
echo <<Even Japanese characters are ok in function names, but be
extra careful with these (see Chapter 5).
EOT;
}
?>

3.1.2 Put parameters Pass to function
Basic syntax: In order to pass parameters to a function, the parameter values ​​need to be enclosed in parentheses and separated by commas when calling the function. Each passed parameter can
be any legal expression, it can be a variable, a constant value, the result of an operator, or even a function call.
Copy code The code is as follows:

function my_new_function($param1, $param2, $param3 , $param4)
{
echo <<You passed in:

$param1: $param1

$ param2: $param2

$param3: $param3

$param4: $param4

DONE;
}
//
// call my new function with some values.
//
$userName = "bobo";
$a = 54;
$b = TRUE;
my_new_function ($userName, 6.22e23, pi(), $a or $b);
?>

Pass by reference: By default, only the value of the variable is passed to the function. Therefore, any changes to this parameter or variable are only valid locally in the function
Copy code The code is as follows:

$ x = 10;
echo "$x is: $x
n";
function change_parameter_value($param1)
{
$param1 = 20;
}
echo "$x is: $x
n";
?>

Output: $x is :10
$x is :10
If your intention is that the function actually modifies the variable passed to it, rather than just processing a copy of its value, then you can use the pass-by-reference function. This is done by using the & character

Copy the code The code is as follows:

function increment_variable(&$increment_me)
{
if (is_int($increment_me) || is_float($increment_me))
{
$increment_me += 1;
}
}
$x = 20.5;
echo "$x is: $x
n"; // prints 20.5
increment_variable(&$x);
echo "$x is now: $x
n"; // prints 21.5
?>

The default value of the parameter
is the specific value at which you expect the parameter to dominate In this case, it is called the default argument value (default argumentvalue)
Copy code The code is as follows:

function perform_sort($arrayData, $param2 = "qsort")
{
switch ($param)
{
case "qsort":
qsort($arrayData);
break;
case "insertion":
insertion_sort($arrayData);
break;
default:
bubble_sort($arrayData);
break;
}
}
?>

Variable number of parameters:
php can pass any number of parameters to the function, and then use func_num_args, func_get_arg and func_get_args get parameter values ​​
Copy code The code is as follows:

function print_parameter_values( )
{
$all_parameters = func_get_args();
foreach ($all_parameters as $index => $value)
{
echo "Parameter $index has the value: $value< br/>n";
}
echo "-----
n";
}
print_parameter_values(1, 2, 3, "fish");
print_parameter_values();
?>

3.1.3 Returning values ​​from functions
Some other languages ​​treat subroutines that only execute some code before exiting and execute a Unlike functions that cause code and return a value to the caller, PHP has a value associated with it when it returns to the caller. For functions without an explicit return value, the return value is null

Copy code The code is as follows:
function does_nothing()
{
}
$ret = does_nothing();
echo '$ret: ' . (is_null($ret) ? '(null)' : $ret) . "
";
?>

If you want to return non-null, use return to associate it with an expression

Copy code The code is as follows:
function is_even_number($number)
{
if (($number % 2 ) == 0)
return TRUE;
else
return FALSE;
}
?>

When you want to return multiple values ​​from a function , it is convenient to pass the result back as an array

Copy the code The code is as follows:
function get_user_name($userid)
{
//
// $all_user_data is a local variable (array) that temporarily
// holds all the information about a user.
//
$all_user_data = get_user_data_from_db($userid);
//
// after this function returns, $all_user_data no
// longer exists and has no value.
//
return $all_user_data["UserName"];
}
?>

3.1.4 Variable scope within functions
Function level variables:
Within the function where they are declared are legal, and their values ​​are not memorized between function calls

Copy code The code is as follows:
$name = "Fatima";
echo "$name: $name
n";
function set_name($new_name)
{
echo "$name: $name
n";
$name = $new_name;
}
set_name("Giorgio");
echo "$name: $name
n" ;
?>

Static variables:
Variables prefixed with static keep their values ​​unchanged between function calls. If a variable is assigned a value when it is declared, it will not change when running In the current script, PHP only performs the assignment when it encounters this variable for the first time

Copy the code The code is as follows:
< ;?php
function increment_me()
{
// the value is set to 10 only once.
static $incr=10;
$incr++;
echo"$incr< ;br/>n";
}
increment_me();
increment_me();
increment_me();
?>

Inside script Declared variables ("global variables")

Copy code The code is as follows:
$name = "Fatima";
echo "$name: $name
n";
function set_name($new_name)
{
echo "$name: $name
$name = $new_name;
}
set_name("Giorgio");
echo "$name: $name
n";
?> ;


l Output result:
$name: Fatima
$name:
$name: Fatima
If a globa is added to the internal group function, then the output result is
$name: Fatima
$name: Fatima
$name: Giorgio
3.1.5 Function scope and availability
3.1.6 Using functions as variables
Copy code The code is as follows:

function Log_to_File($message)
{
// open file and write message
}
function Log_to_Browser($message)
{
// output using echo or print functions
}
function Log_to_Network($message)
{
// connect to server and print message
}
//
// we're debugging now, so we'll just write to the screen
//
$log_type = "Log_to_Browser";
//
// now, throughout the rest of our code, we can just call
// $log_type(message) and change where it goes by simply
// changing the above variable assignment!
//
$log_type("beginning debug output");
?>

But PHP contains many language structures that cannot be used as variable functions. Obvious examples of such structures are echo and print , var_dump, print_r, isset, unset, is_null is_type
3.2 Intermediate code reuse: using and including files
3.2.1 Organizing code into files
Group common functions: If you want to save many functions To a single location, typically a file, that is, a code library
Generate a consistent interface
Copy the code The code is as follows:

// circle is (x, y) + radius
function compute_circle_area($x, $y, $radius)
{
return ($ radius * pi() * pi());
}
function circle_move_location(&$y, &$x, $deltax, $deltay)
{
$x += $deltax;
$y += $deltay;
}
function compute_circumference_of_circle($radius)
{
return array("Circumference" => 2 * $radius * pi());
}
?>

By using functions with consistent names, parameter order, and return values, you can significantly reduce the likelihood of failures and defects in your code.
Copy code The code is as follows:

//
// all routines in this file assume a circle is passed in as
// an array with:
// "X" => x coord "Y" => y coord "Radius" => circle radius
/ /
function circles_compute_area($circle)
{
return $circle["Radius"] * $circle["Radius"] * pi();
}
function circles_compute_circumference($circle )
{
return 2 * $circle["Radius"] * pi();
}
// $circle is passed in BY REFERENCE and modified!!!
function circles_move_circle( &$circle, $deltax, $deltay)
{
$circle["X"] += $deltax;
$circle["Y"] += $deltay;
}
?>

3.2.2 Select file name and location
In order to prevent web users from opening .inc files, we use two mechanisms to prevent this from happening. First, when composing the document directory tree , we ensure that the web server does not allow users to browse or load
we do not want them to perform these actions, covered in Chapter 16 Securing Web Applications, and then configure the browser to allow users to browse .php and .html files, but Cannot browse .inc files
The second way to prevent this problem is not to put the code in the document tree, or save it in another directory, and either explicitly reference this directory in our code, telling PHP to always view it This directory
3.2.3 contains the library file
include and require in the script. The difference between the two is that when the file is not found, require outputs an error, while include outputs a warning.
Copy code The code is as follows:

include('i_dont_exit.inc');
require('i_dont_exit.inc');
?>

Where include and require look for files
You can specify explicit paths:
require("/home/httpd/lib/frontend/table_gen.inc');
require('http: //www.cnblogs.com/lib/datafuncs.inc');
require(d:webappslibsdataconnetions.inc');
If no explicit path is specified, php will look for the file to be included in the current directory. Then look for the directory listed in the include_path setting in the php.ini file.
In Windows it is include_path=".;c:phpinclude;d:webappslibs". Don't forget to restart the web server after setting
include. and require do
Anything included in a script tag is processed as a normal php script
Listing 3-1 and Listing 3-2 show the php script and the simple file used for inclusion
Listing 3. -1
3.2.4 Use includes for page templates






Listing 3-2
Copy code The code is as follows:



Sample


$message = "Well, Howdy Pardner!";
include('printmessage.inc');
?>



File inclusions and function scope
How moving functions from a script to an included file affects function scope and the ability to call them
If a function is in another file, and This file is not included in the current script via include and require, then the call is illegal
To avoid this problem, it is a good idea to include other files at the beginning of the script
When sharing becomes a problem
To avoid this problem. To repeatedly load shared files, you can use require_once() and include_once() language structures to prevent repeated definitions of functions or structures.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/323900.htmlTechArticleFrom this chapter, we understand. Create functions that can be called to reuse code. Pass parameters to functions and get from functions. Return values ​​and interact with variables and data in different parts of the script...
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