


Core technologies for PHP and Mysql web application development Part 1 Php basics-3 Code organization and reuse 2_PHP tutorial
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.
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!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.
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
$ 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
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)
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
function print_parameter_values( )
{
$all_parameters = func_get_args();
foreach ($all_parameters as $index => $value)
{
echo "Parameter $index has the value: $valuen";
}
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
{
}
$ret = does_nothing();
echo '$ret: ' . (is_null($ret) ? '(null)' : $ret) . "
";
?>
{
if (($number % 2 ) == 0)
return TRUE;
else
return FALSE;
}
?>
{
//
// $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"];
}
?>
Function level variables:
Within the function where they are declared are legal, and their values are not memorized between function calls
$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" ;
?>
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
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();
?>
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
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
// 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.
//
// 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.
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
$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.

Setting session cookie parameters in PHP can be achieved through the session_set_cookie_params() function. 1) Use this function to set parameters, such as expiration time, path, domain name, security flag, etc.; 2) Call session_start() to make the parameters take effect; 3) Dynamically adjust parameters according to needs, such as user login status; 4) Pay attention to setting secure and httponly flags to improve security.

The main purpose of using sessions in PHP is to maintain the status of the user between different pages. 1) The session is started through the session_start() function, creating a unique session ID and storing it in the user cookie. 2) Session data is saved on the server, allowing data to be passed between different requests, such as login status and shopping cart content.

How to share a session between subdomains? Implemented by setting session cookies for common domain names. 1. Set the domain of the session cookie to .example.com on the server side. 2. Choose the appropriate session storage method, such as memory, database or distributed cache. 3. Pass the session ID through cookies, and the server retrieves and updates the session data based on the ID.

HTTPS significantly improves the security of sessions by encrypting data transmission, preventing man-in-the-middle attacks and providing authentication. 1) Encrypted data transmission: HTTPS uses SSL/TLS protocol to encrypt data to ensure that the data is not stolen or tampered during transmission. 2) Prevent man-in-the-middle attacks: Through the SSL/TLS handshake process, the client verifies the server certificate to ensure the connection legitimacy. 3) Provide authentication: HTTPS ensures that the connection is a legitimate server and protects data integrity and confidentiality.

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python are both high-level programming languages that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 English version
Recommended: Win version, supports code prompts!

Atom editor mac version download
The most popular open source editor