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

Jul 21, 2016 pm 03:26 PM
php code point and Base application development us technology core organize Reuse

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles