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

Source: Internet
Author: User
Tags array expression functions variables parse error php and php basics valid
From this chapter, we understand

. Create a function that can be called to reuse code

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

The code and function groups are stored in other files, and our scripts contain these files.

3.1 Basic code reuse: Functions

3.1.1 Define and Invoke functions

Keyword function notifies PHP this is a function followed by the name of the function, which can be letters, numbers, characters, or underscores

The function name is followed by the argument list and then the function body. PHP does not support a function that has the same name in other languages but has different argument lists.
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 a 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<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 would
Probably have to is saved in a Unicode format though,
such as UTF-8 (Chapter 5).
//
function Japanese Language のファンクション ()
{
Echo <<<eot
Even Japanese characters are OK in function names, but
Extra careful with these (Chapter 5).
EOT;
}
?>

3.1.2 Pass parameters to the function
Basic syntax: To pass arguments to a function, you need to enclose the parameter values in parentheses in order to call the function, separated by commas. Each parameter that is passed can be
To be any legitimate expression, it can be a variable, a constant value, a result of an operator, or even a function call.
Copy CodeThe code is as follows:
<?php
function My_new_function ($param 1, $param 2, $param 3, $param 4)
{
Echo <<<done
Passed in: <br/>
\ $param 1: $param 1 <br/>
\ $param 2: $param 2 <br/>
\ $param 3: $param 3 <br/>
\ $param 4: $param 4 <br/>
Done;
}
//
The call me new function with some values.
//
$userName = "Bobo";
$a = 54;
$b = TRUE;
My_new_function ($userName, 6.22e23, Pi (), $a or $b);
?>

Passing 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 <br/>\n";
function Change_parameter_value ($param 1)
{
$param 1 = 20;
}
echo "\ $x is: $x <br/>\n";
?>

Output: $x is:10
$x is:10
If your purpose is to actually modify the variables passed to it, not just the copy of its value, then the function that can be passed by reference (reference). This is done by using the & character

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 values for parameters
In the case where you expect the parameter to have a dominant value, it is called the default parameter value (Argumentvalue)
Copy CodeThe code is as follows:
<?php
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 a function and then use Func_num_args, Func_get_arg, and Func_get_args to get the value of the parameter
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 Returns a value from a function
Some other languages distinguish between a subroutine that executes only some code before exiting and a function that causes the value to be returned to the caller, unlike PHP, where all PHP functions are returned to the caller
Has a value associated with it. For functions that do not have an explicit 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, associate it with an expression by returning
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 a 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"];
}
?>

Range of variables within the 3.1.4 function
Function-level variables:
The functions that declare them are valid and do not memorize their values between calls to the function
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 as a prefix variable keeps their values unchanged between function calls, and if you assign a variable when you declare it, PHP performs the assignment only the first time you run the current script.
Copy CodeThe code is as follows:
<?php
function Increment_me ()
{
The value is set to once.
static $INCR = 10;
$INCR + +;
echo "$INCR <br/>\n";
}
Increment_me ();
Increment_me ();
Increment_me ();
?>

Variables declared within 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 you add a Globa to the inner 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:
<?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 and so we'll just write to the screen
//
$log _type = "Log_to_browser";
//
Now, throughout the rest of my 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 a lot of language constructs that cannot be used as variable functions, notably the Echo, print, Var_dump, Print_r, Isset, unset, Is_null Is_type
3.2 Intermediate code reuse: using and including files
3.2.1 To organize code into files
Grouping common functions: If you want to save many functions to a single location, typically a file, the code library
Generate a consistent interface
Copy 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, you can significantly reduce the likelihood of failure and the flaws in your code.
Copy CodeThe code is as follows:
<?php
//
All routines in this file assume a circle be 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 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
To prevent web users from opening the. inc file, we use two mechanisms to prevent this, and first, in the form of the document tree, we make sure that the Web server does not allow users to browse or load
Do not want them to do this, in chapter 16, protect 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 problem is not to put the code in the document tree, or save it in another directory, and either explicitly refer to the directory in our code and tell PHP to always view the directory
3.2.3 include library files in scripts
Include and require, the difference being that when a file is not found, the Require output error and the include output warning.
Copy CodeThe code is as follows:
<?php
Include (' I_dont_exit.inc ');
Require (' i_dont_exit.inc ');
?>

Include and require where to find files
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 you do not specify an explicit path, PHP looks for the files to include in the current directory, and then looks for the directories listed in the Include_path setting in the php.ini file.
In Windows is include_path= ".; C:\php\include;d:\webapps\libs, do not forget to restart the Web server when the settings are complete.
What are the include and require doing?
Any content contained in the script tag is handled as a generic PHP script.
Listing 3-1 and listing 3-2 show PHP scripts and simple files for inclusion
Listing 3-1
3.2.4 include for page templating
<p align= ' center ' >
<b>
<?php echo $message;?>
</b>
</p>
Listing 3-2
Copy CodeThe code is as follows:
<title>Sample</title>
<body>
<?php
$message = "OK, Howdy pardner!";
Include (' Printmessage.inc ');
?>
</body>

File Inclusion and Function scope
How you can affect the scope of functions and the ability to invoke them when moving a function from a script to a containing file.
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 repeated loading of shared files, you can use the require_once () and include_once () language structures to prevent duplicate 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.