Arguments and Return Values Every function call consists of the function name followed by a list of arguments in parentheses.. This function does not require any arguments, so it can be
Trang 1Arguments and Return Values
Every function call consists of the function name followed by a list of arguments in parentheses If there is more than one argument, the list items are separated with commas Some functions do not require any arguments at all, but a pair of
parentheses is still requiredeven if there are no arguments contained in them
The built-in function phpinfo generates a web page that contains a lot of
information about the PHP module This function does not require any arguments,
so it can be called from a script that is as simple as
<?php phpinfo();?>
If you create this script and point a web browser at it, you will see a web page that contains system information and configuration settings
Returning Success or Failure
Because phpinfo generates its own output, you do not need to prefix it with echo, but, for the same reason, you cannot assign the web page it produces to a variable In fact, the return value from phpinfo is the integer value 1
Returning True and False Functions that do not have an explicit
return value usually use a return code to indicate whether their
operation has completed successfully A zero value (FALSE)
indicates failure, and a nonzero value (TRUE) indicates success
The following example uses the mail function to attempt to send an email from a PHP script The first three arguments to mail specify the recipient's email
address, the message subject, and the message body The return value of mail is used in an if condition to check whether the function was successful:
if (mail("chris@lightwood.net",
"Hello", "This is a test email")) {
echo "Email was sent successfully";
}
else {
Trang 2echo "Email could not be sent";
}
If the web server that this script is run on is not properly configured to send email,
or if there is some other error when trying to send, mail will return zero,
indicating that the email could not be sent A nonzero value indicates that the
message was handed off to your mail server for sending
Return Values Although you will not always need to test the
return value of every function, you should be aware that every
function in PHP does return some value
Default Argument Values
The mail function is an example of a function that takes multiple arguments; the recipient, subject, and message body are all required The prototype for mail also specifies that this function can take an optional fourth argument, which can contain additional mail headers
Calling mail with too few arguments results in a warning For instance, a script that contains the following:
mail("chris@lightwood.net", "Hello");
will produce a warning similar to this:
Warning: mail() expects at least 3 parameters, 2 given in
/home/chris/mail.php on line 3
However, the following two calls to mail are both valid:
mail("chris@lightwood.net", "Hello", "This is a test email");
mail("chris@lightwood.net", "Hello", "This is a test email",
"Cc: editor@samspublishing.com");
Trang 3To have more than one argument in your own function, you simply use a comma-separated list of variable names in the function definition To make one of these arguments optional, you assign it a default value in the argument list, the same way you would assign a value to a variable
The following example is a variation of add_tax that takes two argumentsthe net amount and the tax rate to add on $rate has a default value of 10, so it is an optional argument:
function add_tax_rate($amount, $rate=10) {
$total = $amount * (1 + ($rate / 100));
return($total);
}
Using this function, the following two calls are both valid:
add_tax_rate(16);
add_tax_rate(16, 9);
The first example uses the default rate of 10%, whereas the second example
specifies a rate of 9% to be usedproducing the same behavior as the original
add_tax function example
Optional Arguments All the optional arguments to a function must
appear at the end of the argument list, with the required values
passed in first Otherwise, PHP will not know which arguments
you are passing to the function
Variable Scope
The reason values have to be passed in to functions as arguments has to do with variable scopethe rules that determine what sections of script are able to access which variables
The basic rule is that any variables defined in the main body of the script cannot be
Trang 4used inside a function Likewise, any variables used inside a function cannot be seen by the main script
Scope Variables available within a function are said to be local
variables or that their scope is local to that function Variables that
are not local are called global variables
Local and global variables can have the same name and contain
different values, although it is best to try to avoid this to make
your script easier to read
When called, add_tax calculates $total, and this is the value returned
However, even after add_tax is called, the local variable $total is undefined outside that function
The following piece of code attempts to display the value of a global variable from inside a function:
function display_value() {
echo $value;
}
$value = 125;
display_value();
If you run this script, you will see that no output is produced because $value has not been declared in the local scope
To access a global variable inside a function, you must use the global keyword
at the top of the function code Doing so overrides the scope of that variable so that
it can be read and altered within the function The following code shows an
example:
function change_value() {
global $value;
echo "Before: $value <br>";
$value = $value * 2;
}
Trang 5$value = 100;
display_value();
echo "After: $value <br>";
The value of $value can now be accessed inside the function, so the output produced is as follows:
Before: 100
After: 200
Trang 6Using Library Files
After you have created a function that does something useful, you will probably want to use it again in other scripts Rather than copy the function definition into each script that needs to use it, you can use a library file so that your function needs to be stored and maintained in only one place
Before you go any further, you should create a library file called tax.php that contains both the add_tax and add_tax_rate functions but no other PHP code
Using Library Files A library file needs to enclose its PHP code
inside <?php tags just like a regular script; otherwise, the
contents will be displayed as HTML when they are included in a
script
Including Library Files
To incorporate an external library file into another script, you use the include keyword The following includes tax.php so that add_tax can be called in that script:
include "tax.php";
$price = 95;
echo "Price before tax: $price <br>";
echo "Price after tax: ";
echo add_tax($price);
Theinclude path Setting By default, include searches only
the current directory and a few system locations for files to be
included If you want to include files from another location, you
can use a path to the file
You can extend the include path to include other locations
without a path being required by changing the value of the
include_path setting Refer to Lesson 23, "PHP," for more
information
Trang 7You can use the include_once keyword if you want to make sure that a library file is loaded only once If a script attempts to define the same function a second time, an error will result Using include_once helps to avoid this, particularly when files are being included from other library files It is often useful to have a library file that includes several other files, each containing a few functions, rather than one huge library file
Require The require and require_once instructions
work in a similar way to include and include_once but
have subtly different behavior In the event of an error, include
generates a warning, but the script carries on running as best it
can A failure from a require statement causes the script to exit
immediately