SoFunction
Updated on 2025-04-08

Core technologies for PHP and Mysqlweb application development Part 1 Php basics-3 Code organization and reuse 2

From this chapter, we understand

.Create functions that can be called to reuse code

.Pass the parameters to the function and interact from the function return value and variables and data in different parts of the script

.Save code and function groups into other files, and our script contains these files.

3.1 Basic code reuse: functions

3.1.1 Defining and calling functions

Keyword function notifies php This is a function followed by the name of the function, which can be a letter, number, character or underscore

The function name is followed by the parameter list, followed by the function body. PHP does not support this feature in functions with the same name but different parameter lists in other languages.
Copy the codeThe code is as follows:

<?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/
// on line 55
//
// Function names cannot start with numbers
//
function 234letters()
{
echo "I am not valid<br/>\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 Japanese のファンクシシン()
{
echo <<<EOT
Even Japanese characters are ok in function names, but be
extra careful with these (see Chapter 5).
EOT;
}
?>

3.1.2 Passing parameters to functions
Basic syntax: In order to pass parameters to a function, when calling the function, the parameter values ​​need to be enclosed in brackets and separated by commas. Each passed parameter can
Therefore, any legal expression can be the result of variables, constant values, operators, or even function calls.
Copy the codeThe code is as follows:

<?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 valid in the function
Copy the codeThe code is as follows:

$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 purpose is that the function actually modifies the variable passed to it, not just processing copies of its values, then the function passed with reference. This is done by using & characters

Copy the codeThe code is as follows:

<?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
?>

Default value of parameters
In cases where you expect the parameter to have a specific value that is dominant, it is called the default argument value
Copy the codeThe code is as follows:

<?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 number of parameters:
PHP can pass any number of parameters to a function, and then use func_num_args, func_get_arg and func_get_args to obtain parameter values.
Copy the codeThe code is as follows:

<?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 Returning value from function
Some other languages ​​distinguish between subroutines that only execute some code before exiting from functions that cause code and return the value to the caller. PHP is different from them. All php functions return to the caller.
There is a value associated with it. For functions without explicit return values, the return value is null
Copy the codeThe code is as follows:

<?php
function does_nothing()
{
}
$ret = does_nothing();
echo '$ret: ' . (is_null($ret) ? '(null)' : $ret) . "<br/>";
?>

If you want to return non-null, use return to associate it with an expression
Copy the codeThe code is as follows:

<?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 to
Copy the codeThe code is as follows:

<?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 Variable ranges within a function
Function-level variables:
Declare their function to be legal and do not remember their values ​​between calls to the function
Copy the codeThe code is as follows:

<?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 with static as prefix keep their values ​​unchanged between function calls. If the variable is assigned to it when declaring it, when running the current script, php only performs assignment when the variable is first encountered.
Copy the codeThe 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();
?>

Variables declared in scripts ("global variables")
Copy the codeThe code is as follows:

<?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";
?>

lOutput result:
$name: Fatima
$name:
$name: Fatima
If you add a globa to the internal group function, then the result will be output
$name: Fatima
$name: Fatima
$name: Giorgio
3.1.5 Function range and availability
3.1.6 Use functions as variables
Copy the codeThe code is as follows:

<?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");
?>

However, php contains many language structures that cannot be used as variable functions. Obviously examples of this structure 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 a file
Grouping common functions: If you want to save many functions to a single location, the typical case is a file, that is, a code library
Generate a consistent interface
Copy the codeThe code is as follows:

<?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 to have a consistent name, parameter order, and return value, the possibility of failure and defects in the code can be significantly reduced.
Copy the codeThe code is as follows:

<?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
In order to prevent web users from opening .inc files, we use two mechanisms to prevent this from happening. First, in the document directory tree, we ensure that the web server does not allow users to browse or load
Don't want them to do these operations, introduced in Chapter 16 Protecting the web application, and then the configuration browser will allow the user to browse .php and .html files, but cannot browse .inc files
The second way to prevent this problem does not put the code in the document tree, or store it in other directories, and either explicitly reference this directory in our code, notifying php that always view this directory
3.2.3 Including library files in scripts
include and require, the two differences are that when the file cannot be found, require output errors, and include outputs warnings.
Copy the codeThe code is as follows:

<?php
include('i_dont_exit.inc');
require('i_dont_exit.inc');\
?>

Where to find files include and require
You can specify clear paths:
require("/home/httpd/lib/frontend/table_gen.inc');
require('/lib/');
require(d:\webapps\libs\data\');
If no explicit path is specified, php looks for the file to be included in the current directory, and then looks for the directory listed in the include_path setting in the file.
After the windows is include_path=".;c:\php\include;d:\webapps\libs" is set up, do not forget to restart the web server.
What does include and require do
Anything contained in the script tag is handled as a general php script.
Listing 3-1 and Listing 3-2 show php scripts and simple files for included
Listing 3-1
3.2.4 Use the inclusion to template the page
<p align='center'>
<b>
<?php echo $message; ?>
</b>
</p>
Listing 3-2
Copy the codeThe code is as follows:

<html>
<head>
<title>Sample</title>
</head>
<body>
<?php
$message = "Well, Howdy Pardner!";
include('');
?>
</body>
</html>

File Inclusion and Function Scope
When moving functions from scripts to include files, how will it affect the scope of functions 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
In order to avoid repeated loading of shared files, you can use require_once() and include_once() language structure to prevent duplicate definition of functions or structures.