PHP and Mysqlweb application development core technology Part 1 Php basics-3 Code Organization and reuse 2

Source: Internet
Author: User
Tags parse error php basics

From this chapter, we understand

. Create a function that can be called to reuse code

. Pass the parameter to the function and interact with the variable and data in different parts of the function return value and script.

. Save the code and function group to other files, and our script contains these files.

3.1 reuse of basic code: Functions

3.1.1 define and call Functions

The keyword function notifies php that this is a function followed by the function name. It can be letters, numbers, characters, or underscores.

The function name is followed by the parameter list and then the function body. Php does not support functions with the same name but different parameter lists in other languages.Copy 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/playing. php
// On line 55
//
// Function names cannot start with numbers
//
Function 234 letters ()
{
Echo "I am not valid <br/> \ n ";
}
//
// Extended characters are OK.
//
Function gr ü 1_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 Unicom ()
{
Echo <EOT
Even Japanese characters are OK in function names, but be
Extra careful with these (see Chapter 5 ).
EOT;
}
?>

3.1.2 PASS Parameters to Functions
Basic Syntax: to pass a parameter to a function, you must enclose the parameter values in brackets and separate them with commas. Each passed parameter can be
It can be the result of a variable, constant value, operator, or even a function call.Copy 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 modification to this parameter or variable is only effective in the local part of the function.Copy 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 you want a function to actually modify the variables passed to it, rather than just copying the values, you can use the reference function. This is done by using & characters

Copy 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 the Parameter
The default argumentvalue is called when you want the parameter to have a specific value that is dominant)Copy codeThe Code is as follows: <? Php
Function compute m_sort ($ arrayData, $ param2 = "qsort ")
{
Switch ($ param)
{
Case "qsort ":
Qsort ($ arrayData );
Break;
Case "insertion ":
Insertion_sort ($ arrayData );
Break;
Default:
Bubble_sort ($ arrayData );
Break;
}
}
?>

Variable parameters:
Php can pass any number of parameters to the function, and then use func_num_args, func_get_arg, and func_get_args to obtain the parameter values.Copy 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 return value from Function
Some other languages differentiate the subroutines that only execute some code before exiting from the ones that cause code execution and return the value to the caller. php is different from them. All php functions return to the caller.
Each value is associated with it. For a function without a clear return value, the return value is null.Copy 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 a non-null value, use return to associate it with an expression.Copy 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 the function, it is convenient to pass the result back as an array.Copy 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 range in Function
Function-level variables:
The declared functions are valid and do not remember their values between function calls.Copy 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:
Static variables used as prefixes keep their values unchanged between function calls. If a variable is assigned a value during the declaration, php only assigns a value when the current script is run for the first time.Copy 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 the script ("global variables ")Copy 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 ";
?>

L output result:
$ Name: Fatima
$ Name:
$ Name: Fatima
If a globa is added to the internal group function, the output result is
$ Name: Fatima
$ Name: Fatima
$ Name: Giorgio
3.1.5 function range and availability
3.1.6 use a function as a variableCopy 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 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. The obvious examples of such structures are echo, print, var_dump, print_r, isset, unset, and is_null is_type.
3.2 intermediate code reuse: use and include files
3.2.1 organize code into a file
Group common functions: If you want to save many functions to a single location, a file is typically called code library)
Generate consistent InterfacesCopy codeThe Code is as follows: <? Php
// Circle is (x, y) + radius
Function compute_circle_area ($ x, $ y, $ radius)
{
Return ($ radius * 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 consistent names, Parameter order, and return values, you can significantly reduce the possibility of failure and defects in code.Copy codeThe Code is as follows: <? Php
//
// All routines in this file assume a circle is passed in
// An array:
// "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 the file name and location
To prevent web users from opening. inc files, we use two mechanisms to prevent this situation. First, in the document directory tree, we ensure that the web server does not allow users to browse or load files.
I don't want them to do this. I will introduce them in chapter 16 Protection Web applications. Then, I will 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 include the code in the document tree, or store it in another directory, or explicitly reference this directory in our code, notifying php to always view this directory.
3.2.3 include the library file in the script
The difference between include and require is that when the file cannot be found, require outputs an error while include outputs a warning.Copy 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 a clear path:
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 clear path is specified, php searches for the files to be included in the current directory, and then finds the directories listed in the include_path setting in the php. ini file.
In windows, do not forget to restart the web server after setting include_path = ". c: \ php \ include; d: \ webapps \ libs.
What does include and require do?
Any content contained in the script tag is processed as a common php script.
Listing 3-1 and listing 3-2 show php scripts and simple files for inclusion
Listing 3-1
3.2.4 use the content for page templatification
<P align = 'center'>
<B>
<? Php echo $ message;?>
</B>
</P>
Listing 3-2Copy codeThe Code is as follows: <Head>
<Title> Sample </title>
</Head>
<Body>
<? Php
$ Message = "Well, Howdy Pardner! ";
Include ('printmessage. inc ');
?>
</Body>
</Html>

File Inclusion and function range
How does one affect the function scope and the ability to call functions when moving functions from scripts to include files.
If a function is in another file and the file is not included in the current script through include and require, the call is invalid.
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 duplicate shared files, use the require_once () and include_once () language structures to prevent repeated definitions of functions or structures.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.