PHP and Mysqlweb application development core technologies part 1 Php base 3 code organization and reuse 2

  • 2020-05-09 18:19:34
  • OfStack

From this chapter we learn

.create functions that can be called to reuse the code

Pass arguments to functions and interact with variables and data from function return values and different parts of the script

.store the code and function groups in other files and include them in our script.

3.1 basic code reuse: functions

3.1.1 define and call functions

The keyword function informs php that this is a function, followed by the name of the function, which can be a letter, a number, a character, or an underscore

The function name is followed by the argument list, and then the function body. For functions with the same name but different parameter lists in other languages, php does not support this 1 feature.
 
<?php 
function booo_spooky() 
{ 
echo "I am booo_spooky. This name is okay!<br/>\n"; 
} 
function ____333434343434334343() 
{ 
echo <<<DONE 
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<br/>\n"; 
} 
// 
// Extended characters are ok. 
// 
function gr u ß_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  Japan � の フ ァ ン ク シ ョ ン () 
{ 
echo <<<EOT 
Even Japanese characters are ok in function names, but be 
extra careful with these (see Chapter 5). 
EOT; 
} 
?> 

3.1.2 pass the parameters to the function
Basic syntax: to pass arguments to a function, you need to enclose the argument values in parentheses, separated by commas, when calling a function. Each passed parameter can be
To be any legal expression, it can be a variable, a constant value, the result of an operator, or even a function call.
 
<?php 
function my_new_function($param1, $param2, $param3, $param4) 
{ 
echo <<<DONE 
You passed in: <br/> 
\$param1: $param1 <br/> 
\$param2: $param2 <br/> 
\$param3: $param3 <br/> 
\$param4: $param4 <br/> 
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 locally valid in the function
 
$x = 10; 
echo "\$x is: $x<br/>\n"; 
function change_parameter_value($param1) 
{ 
$param1 = 20; 
} 
echo "\$x is: $x<br/>\n"; 
?> 

Output: $x is :10
$x is :10
If your goal is for the function to actually modify the variables passed to it, instead of just handling copies of their values, you can use the function passed by reference (reference). This is done by using the & character

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

The default value of the parameter
In cases where you expect the parameter to have a specific value of dominance, this is called the default parameter value (default argumentvalue)
 
<?php 
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 quantity parameters:
php can pass any number of arguments to a function, and then get the parameter values using func_num_args, func_get_arg, and func_get_args
 
<?php 
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 "-----<br/>\n"; 
} 
print_parameter_values(1, 2, 3, "fish"); 
print_parameter_values(); 
?> 

3.1.3 return value from function
Unlike some other languages that distinguish between subroutines that execute only 1 bit of code before exiting and functions that execute 1 and return the value to the caller, php differs from all php functions that return the caller
There's a value associated with it. For functions that do not have an explicit return value, the return value is null
 
<?php 
function does_nothing() 
{ 
} 
$ret = does_nothing(); 
echo '$ret: ' . (is_null($ret) ? '(null)' : $ret) . "<br/>"; 
?> 

If you want to return a non-null, associate it with an expression using return
 
<?php 
function is_even_number($number) 
{ 
if (($number % 2) == 0) 
return TRUE; 
else 
return FALSE; 
} 
?> 

When you want to return multiple values from a function, passing the result back as an array is a convenient way
 
<?php 
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 range of variables within a function
Function level variables:
Declare them legal within functions, and do not remember their values between function calls
 
<?php 
$name = "Fatima"; 
echo "\$name: $name<br/>\n"; 
function set_name($new_name) 
{ 
echo "\$name: $name<br/>\n"; 
$name = $new_name; 
} 
set_name("Giorgio"); 
echo "\$name: $name<br/>\n"; 
?> 

Static variables:
Variables prefixed with static keep their values constant between function calls, and if they are assigned when the variable is declared, php only performs the assignment the first time the variable is encountered when running the current script
 
<?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(); 
?> 

Variables declared in the script (" global variables ")
 
<?php 
$name = "Fatima"; 
echo "\$name: $name<br/>\n"; 
function set_name($new_name) 
{ 
echo "\$name: $name<br/>\n"; 
$name = $new_name; 
} 
set_name("Giorgio"); 
echo "\$name: $name<br/>\n"; 
?> 

l output results:
$name: Fatima
$name:
$name: Fatima
If you add 1 globa to the internal group function, the output will be the result
$name: Fatima
$name: Fatima
$name: Giorgio
3.1.5 function scope and availability
3.1.6 use functions as variables
 
<?php 
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 constructs that cannot be used as functions of variables. The obvious examples of this construction are echo, print, var_dump, print_r, isset, unset, is_null, is_type
3.2 intermediate code reuse: use and include files
3.2.1 organize the code into files
Group common functions: if you want to save many functions in a single 1 location, the typical case is a single file, or code base (code library)
Generate a 1-bit interface
 
<?php 
// 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 this function with a 1-lead name, parameter order, and return value, you can significantly reduce the likelihood of failure and defects in your code.
 
<?php 
// 
// 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
To prevent web users from opening.inc files, we use two mechanisms to prevent this from happening. First, in the directory tree that makes up the documents, we make sure that the web server does not allow users to browse or load
You don't want them to do this, as described in chapter 16 protecting web applications, then, the browser will be configured to allow users to browse.php and.html files, but not.inc files
The second way to prevent this problem is not to put the code in the document tree, or into another directory, and either explicitly reference this directory in our code, notifying php to always view this directory
3.2.3 include library files in the script
The difference between include and require is that require prints an error when a file cannot be found, while include prints a warning.
 
<?php 
include('i_dont_exit.inc'); 
require('i_dont_exit.inc');\ 
?> 

Where can include and require find files
You can specify a specific route:
require("/home/httpd/lib/frontend/table_gen.inc');
require('http://www.cnblogs.com/lib/datafuncs.inc');
require(d:\webapps\libs\data\connetions.inc');
If no explicit path is specified, php looks for the file to include in the current directory, and then looks for the directory listed in the include_path setting in the php.ini file.
In windows include_path = ".; c: \ php \ include; d:\webapps\libs "don't forget to restart web server after setting up.
What did include and require do
Anything contained in the script tag is treated as a 1 - like php script.
Listings 3-1 and 3-2 show the php script and simple files for inclusion
Listing 3 to 1
3.2.4 use include for page templating
< p align='center' >
< b >
< ?php echo $message; ? >
< /b >
< /p >
Listing 3 to 2
 
<html> 
<head> 
<title>Sample</title> 
</head> 
<body> 
<?php 
$message = "Well, Howdy Pardner!"; 
include('printmessage.inc'); 
?> 
</body> 
</html> 

File include and function scope
How does moving functions from scripts to include files affect their scope and ability to call them?
If one function is in another file and the file is not included in the current script through 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 reloading Shared files, you can use the require_once() and include_once() language constructs to prevent the problem of function or structure redefinition

Related articles: