PHP and Mysqlweb Application Development core Technology part 1th PHP Basics-3 Code organization and Reuse 2_php tutorials

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 parameters to the function and interact with variables and data from the function return value and the different parts of the script

. Store code and function groups in other files, and our scripts contain them.

3.1 Basic code reuse: Functions

3.1.1 Defining and calling functions

Keyword function notification PHP 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, followed by the function body. PHP does not support this feature in other languages where the name is the same, but the parameter list is different.
Copy CodeThe code is as follows:
function Booo_spooky ()
{
echo "I am booo_spooky. This name is okay!
\ n ";
}
function ____333434343434334343 ()
{
Echo << I am ____333434343434334343. This was an awfully
Unreadable function name. But it's 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 is OK.
//
function Grüß_dich ()
{
echo "Extended characters is OK, but is careful!
\ n ";
}
//
Really extended characters is OK too!! Your file would
Probably has the saved in a Unicode format though,
such as UTF-8 (see Chapter 5).
//
function Japanese Language のファンクション ()
{
Echo << Even Japanese characters is ok in function names
Extra careful with these (see Chapter 5).
EOT;
}
?>

3.1.2 Passing parameters to the function
Basic syntax: In order to pass parameters to a function, you need to enclose the parameter values in parentheses, separated by commas, when calling the function. Each passed parameter can be
As any legal expression, it can be the result of a variable, a constant value, an operator, or even a function call.
Copy CodeThe code is as follows:
function My_new_function ($param 1, $param 2, $param 3, $param 4)
{
Echo << You passed in:

\ $param 1: $param 1

\ $param 2: $param 2

\ $param 3: $param 3

\ $param 4: $param 4

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 CodeThe code is as follows:
$x = 10;
echo "\ $x is: $x
\ n ";
function Change_parameter_value ($param 1)
{
$param 1 = 20;
}
echo "\ $x is: $x
\ n ";
?>

Output: $x is:10
$x is:10
If your goal is for a function to actually modify a variable passed to it, rather than just a copy of its value, you can pass the function by reference (reference). This is done by using the & character

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

Default values for parameters
In the case of a specific value that you expect the parameter to have a dominant position, it is called the default parameter value (Argumentvalue)
Copy CodeThe code is as follows:
function Perform_sort ($arrayData, $param 2 = "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 arguments to the function, and then use Func_num_args, Func_get_arg, and Func_get_args to get the parameter values
Copy CodeThe 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
\ n ";
}
echo "-----
\ n ";
}
Print_parameter_values (1, 2, 3, "fish");
Print_parameter_values ();
?>

3.1.3 Returning a value from a function
Some other languages take a subroutine that executes only some code before exiting and executes a code that causes the value to be returned to the caller, and PHP differs from them in that all PHP functions return to the caller
Has a value associated with it. For functions with no explicit return value, the return value is null
Copy CodeThe 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 CodeThe 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 CodeThe 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"];
}
?>

Range of variables within the 3.1.4 function
Function-level variables:
The functions that declare them are legitimate, and their values are not remembered between calls to the function
Copy CodeThe 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:
Static variables that are prefixed to the function call keep their values constant, and if they are assigned a value when declaring a variable, PHP executes the assignment only when the current script is run, when it first encounters the variable.
Copy CodeThe code is as follows:
function Increment_me ()
{
The value is set to ten only once.
static $INCR = 10;
$INCR + +;
echo "$INCR
\ n ";
}
Increment_me ();
Increment_me ();
Increment_me ();
?>

Variables declared within a script ("Global Variables")
Copy CodeThe 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 ";
?>

L Output Result:
$name: Fatima
$name:
$name: Fatima
If you add a globa to an internal group function, the output
$name: Fatima
$name: Fatima
$name: Giorgio
3.1.5 function Scope and availability
3.1.6 to use functions as variables
Copy CodeThe 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 constructs that cannot be used as variable functions, such as ECHO, Print, Var_dump, Print_r, Isset, unset, Is_null Is_type
3.2 Intermediate code reuse: using and including files
3.2.1 Organize your code into files
Grouping common functions: If you want to save many functions in a single location, typically a file, the code library
Generating a consistent interface
Copy CodeThe 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 this function with a consistent name, parameter order, and return value, you can significantly reduce the likelihood of failure and flaws in your code.
Copy CodeThe code is as follows:
//
All routines in this file assume a circle are passed in as
An array with:
"X" = x coord "y" = y coord "radius" = 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 on by REFERENCE and modified!!!
Function circles_move_circle (& $circle, $deltax, $deltay)
{
$circle ["X"] + = $deltax;
$circle ["Y"] + = $deltay;
}
?>

3.2.2 Choosing a file name and location
To prevent web users from opening. inc files, we use two mechanisms to prevent this from happening, first, in the constituent document tree, we ensure that the Web server does not allow users to browse or load
Do not want them to do these operations, described in Chapter 16 securing the Web application, 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 is not to put the code in the document tree, or into another directory, and either explicitly refer to the directory in our code, and notify PHP to always view the directory
3.2.3 include library files in the script
The two differences between include and require are that when a file is not found, the require output is incorrect, and the include output warns.
Copy CodeThe code is as follows:
Include (' I_dont_exit.inc ');
Require (' i_dont_exit.inc ');
?>

Where to find files for 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 explicit path is specified, PHP looks in the current directory for the files to include, and then looks for the directories listed in the Include_path settings in the php.ini file.
In Windows is include_path= ".; C:\php\include;d:\webapps\libs "After the setup is complete, do not forget to restart the Web server.
What the include and require do
Anything contained in the script tag is handled as a generic PHP script.
Listing 3-1 and listing 3-2 show the PHP script and the simple files for inclusion
Listing 3-1
3.2.4 include for page templating






Listing 3-2
Copy CodeThe code is as follows:


<title>Sample</title>


$message = "Well, Howdy pardner!";
Include (' Printmessage.inc ');
?>



File Inclusion and Function scope
When you move a function from a script to a containing file, how it affects the scope of the function and the ability to invoke it.
If a 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 repeatedly loading shared files, you can use the require_once () and include_once () language constructs to prevent repetitive definitions of functions or structures

http://www.bkjia.com/PHPjc/323900.html www.bkjia.com true http://www.bkjia.com/PHPjc/323900.html techarticle from this chapter, we understand. Create functions that can be called to reuse code. Pass parameters to the function and interact with the variables and data from the function return values and the different parts of the script ...

  • Related Article

    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.