|
Functions
This chapter describes:
- How to define functions.
- How to pass references to and returning a reference from functions.
User Defined Functions
PHP supports user defined functions like in other languages, with some special features:
- By default, arguments are passed by value. But arguments can also be passed as references.
- Arguments can be assigned with default values.
- Functions can return values or references.
- Function names can also be string expressions. This is called variable functions.
- Functions can be defined inside another code block, or function.
Passing and Returning References
The following sample script shows how references can be passed to and returned from
a function, FunctionTest.php:
<?php # FunctionTest.php
# Copyright (c) 2002 by Dr. Herong Yang, http://www.herongyang.com/
#
print "\nPassing arguments as references:\n";
$x = "Apple";
$y = "Orange";
swap($x,$y);
print " x = $x\n";
print " y = $y\n";
#
print "\nReturning a reference:\n";
$x = 10;
$y = &ref($x);
$x = 20;
print " y = $y\n";
#
function swap(&$a, &$b) {
$c = $b;
$b = $a;
$a = $c;
}
function &ref(&$a) {
return $a;
}
?>
Here is the output of the program:
Passing arguments as references:
x = Orange
y = Apple
Returning a reference:
y = 20
I am sure you know why we getting this output.
|