0% found this document useful (0 votes)
5 views

Working with Functions

This document provides an overview of PHP functions, including how to define, call, and return values from functions, as well as variable scope and accessing global variables. It covers advanced topics such as passing arguments by reference, using default values for arguments, and utilizing static variables to maintain state between function calls. Additionally, it discusses the importance of checking for function existence before invocation.

Uploaded by

Vijeth s kulal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Working with Functions

This document provides an overview of PHP functions, including how to define, call, and return values from functions, as well as variable scope and accessing global variables. It covers advanced topics such as passing arguments by reference, using default values for arguments, and utilizing static variables to maintain state between function calls. Additionally, it discusses the importance of checking for function existence before invocation.

Uploaded by

Vijeth s kulal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 56

Unit 1

PHP Language Structure


Working With Functions
• How to define and call functions .
• How to pass values to functions and receive values
in return .
• How to call a function dynamically using a string
stored in a variable .
• How to access global variables from within a
function .
• How to give a function a “memory” .
• How to pass data to functions by reference .
• How to create anonymous functions .
• How to verify that a function exists before calling it .
Functions
• A function is a self-contained block of code that
can be called by your scripts.
• When called, the function’s code is executed.
You can pass values to a function, which will
then use them appropriately.
• When finished, a function can pass a value
back to the calling code.
Calling Functions
• Functions come in two flavors—those built in to
the language and those you define yourself. PHP
has hundreds of built-in functions.
• Ex: print (“Hello Web!”);
• A function call consists of the function name
followed by parentheses.
• If you want to pass information to the function,
you place it between these parentheses.
• A piece of information passed to a function in
this way is called an argument.
Calling Functions
• Some functions require that more than one
argument be passed to them, separated by
commas.
• some_function($an_argument,
$another_argument);
• print() is typical for a function in that it returns
a value.
• The abs() function, for example, requires a
signed numeric value and returns the absolute
value of that number.
Calling Functions
• Ex: Calling the Built-in abs() Function
<html>
<head>
<title>Listing 6.1</title>
</head>
<body>
<?php
$num = -321;
$newnum = abs( $num );
echo $newnum;
Calling Functions
//prints “321”
?>
</body>
</html>
• In this example, we assign the value -321 to a
variable $num. We then pass that variable to the
abs() function, which makes the necessary
calculation and returns a new value. We assign this
to the variable $newnum and display the result.
• You can call user-defined functions in exactly the
same way that we have been calling built-in
functions.
Defining a Function
• You can define your own functions using the
function statement:
function some_function($argument1,
$argument2) {
//function code here }
• The name of the function follows the function
statement and precedes a set of parentheses.
• If your function requires arguments, you must
place comma separated variable names within
the parentheses.
Defining a Function
• These variables will be filled by the values
passed to your function. Even if your function
doesn’t require arguments, you must
nevertheless supply the parentheses.
• Ex: Declaring a Function
<html>
<head>
<title>Listing 6.2</title>
</head>
<body>
Defining a Function
<?php
function bighello() {
echo “<h1>HELLO!</h1>”;
}
bighello();
?>
</body>
</html>
• We declared a function, bighello(), that requires no
arguments. Because of this, we leave the
parentheses empty.
Defining a Function
Ex: Declaring a Function That Requires an
Argument
<html>
<head>
<title>Listing 6.3</title>
</head>
<body>
<?php
function printBR($txt) {
Defining a Function
echo “$txt<br> \n”;
}
printBR(“This is a line”);
printBR(“This is a new line”);
printBR(“This is yet another line”);
?>
</body>
</html>
• Unlike variable names, function names are not
case sensitive.
Defining a Function
• The printBR() function expects a string, so we
place the variable name $txt between the
parentheses when we declare the function.
• Whatever is passed to printBR() will be stored
in the $txt variable. Within the body of the
function, we print the $txt variable, appending
a element and a newline character to it.
Returning Values from User-Defined Functions
• If your function has transformed a string that
you have provided, you may wish to get the
amended string back so that you can pass it to
other functions.
• A function can return a value using the return
statement in conjunction with a value.
• The return statement stops the execution of
the function and sends the value back to the
calling code.
Returning Values from User-Defined Functions
Ex: A Function That Returns a Value
<html>
<head>
<title>Listing 6.4</title>
</head>
<body>
<?php
function addNums($firstnum, $secondnum) {
Returning Values from User-Defined Functions
$result = $firstnum + $secondnum;
return $result;
}
echo addNums(3,5);
//will print “8”
?>
</body>
</html>
Returning Values from User-Defined Functions
• addNums() should be called with two numeric
arguments.
• These are stored in the variables $firstnum and
$secondnum.
• Predictably, addNums() adds the numbers
contained in these variables and stores the
result in a variable called $result.
• The return statement can return a value or
nothing at all.
Returning Values from User-Defined Functions
• The value can be hard-coded: return 4;
• It can be the result of an expression:
return $a/$b;
• It can be the value returned by yet another
function call:
return another_function($an_argument);
Variable Scope
• A variable declared within a function remains
local to that function.
• In other words, it will not be available outside
the function or within other functions.
• Ex: Variable Scope: A Variable Declared Within
a Function Is Unavailable Outside the Function
<html>
<head>
<title>Listing 6.5</title>
</head>
Variable Scope
<body>
<?php
function test() {
$testvariable = “this is a test variable”;
}
echo “test variable: $testvariable<br>”;
?>
</body>
</html>
Variable Scope
• The value of the variable $testvariable is not
printed. This is because no such variable exists
outside the test() function.
• Note that the attempt to access a nonexistent
variable does not cause an error.
• Similarly, a variable declared outside a function
will not automatically be available within it.
Accessing Variables with the global Statement
• From within one function, you cannot (by
default) access a variable defined in another
function or elsewhere in the script.
• Within a function, if you attempt to use a
variable with the same name, you will only set
or access a local variable.
Accessing Variables with the global Statement
• Ex: Variables Defined Outside Functions Are
Inaccessible from Within a Function by Default
<html>
<head>
<title>Listing 6.6</title>
</head>
<body>
<?php
$life = 42;
Accessing Variables with the global Statement
function meaningOfLife() {
echo “The meaning of life is $life<br>”;
}
meaningOfLife();
?>
</body>
</html>
Accessing Variables with the global Statement
• The meaningOfLife() function does not have
access to the $life variable; $life is empty when
the function attempts to print it.
• Occasionally, you may want to access an
important variable from within a function
without passing it in as an argument.
• This is where the global statement comes into
play.
Accessing Variables with the global Statement
• Ex: Accessing Global Variables with the global
Statement
<html>
<head>
<title>Listing 6.7</title>
</head>
<body>
<?php
$life=42;
Accessing Variables with the global Statement
function meaningOfLife() {
global $life;
echo "The meaning of life is $life<br>";
}
meaningOfLife();
?>
</body>
</html>
Saving State Between Function Calls with the static
Statement
• Variables within functions have a short span.
They come into being when the function is
called and die when execution is finished.
• However, you may want to give a function a
rudimentary memory.
• Assume that we want a function to keep track
of the number of times it has been called so
that numbered headings can be created by a
script. We could, use the global statement.
Saving State Between Function Calls with the static
Statement
• Ex: Using the global Statement to Remember the Value of
a Variable Between Function Calls
<html>
<head>
<title>Listing 6.8</title>
</head>
<body>
<?php
$num_of_calls = 0;
function numberedHeading($txt) {
global $num_of_calls;
$num_of_calls++;
Saving State Between Function Calls with the static
Statement
echo “<h1>$num_of_calls. $txt</h1>”;
}
numberedHeading(“Widgets”);
echo “<p>We build a fine range of widgets</p>”;
numberedHeading(“Doodads”);
echo “<p>Finest in the world</p>”;
?>
</body>
</html>
Saving State Between Function Calls with the static
Statement

• We declare a variable, $num_of_calls, outside


the function numberedHeading(). We make
this variable available to the function using the
global statement.
• Every time numberedHeading() is called,
$num_of_calls is incremented. We can then
print out a heading complete with a heading
number.
• This is not the most elegant solution. Functions
that use the global statement cannot be read
as standalone blocks of code.
Saving State Between Function Calls with the static
Statement

• In reading or reusing them, we need to look


out for the global variables that they
manipulate.
• This is where the static statement can be
useful. If you declare a variable within a
function in conjunction with the static
statement, the variable remains local to the
function, and the function “remembers” the
value of the variable from execution to
execution.
Saving State Between Function Calls with the static
Statement

• Ex: Using the static Statement to Remember


the Value of a Variable Between Function Calls
</head>
<body>
<?php
function numberedHeading($txt) {
static $num_of_calls = 0;
$num_of_calls++;
echo "<h1>$num_of_calls. $txt</h1>";
}
Saving State Between Function Calls with the static
Statement

numberedHeading("Widgets");
echo "<p>We build a fine range of widgets</p>";
numberedHeading("Doodads");
echo "<p>Finest in the world</p>";
?>
</body>
</html>
Saving State Between Function Calls with the static
Statement

• The numberedHeading() function has become


entirely self-contained. When we declare the
$num_of_calls variable, we assign an initial
value to it.
• This assignment is made when the function is
first called. This initial assignment is ignored
when the function is called a second time.
• Instead, the code remembers the previous
value of $num_of_calls. We can now paste the
numberedHeading() function into other scripts
without worrying about global variables.
More About Arguments
• In this section, you’ll look at a technique for
giving your arguments default values and
explore a method of passing variables by
reference rather than by value. This means that
the function is given an alias of the original
value rather than a copy of it.
Setting Default Values for Arguments
• PHP gives you a feature to help build flexible
functions. Until now, we’ve said that some
functions require one or more arguments. By
making some arguments optional, you can
render your functions.
• Lets create a useful little function that wraps a
string in an HTML font element. We want to
give the user of the function the chance to
change the font element’s size attribute, so we
demand a $size argument in addition to the
string
Setting Default Values for Arguments
• Ex: A Function Requiring Two Arguments
<html>
<head>
<title>Listing 6.10</title>
</head>
<body>
<?php
function fontWrap($txt, $size) {
echo "<font size=\"$size\"
face=\"Helvetica, Arial, Sans-Serif\">
Setting Default Values for Arguments
$txt</font>";
}
fontWrap("A heading<br>",5);
fontWrap("some body text<br>",3);
fontWrap("some more body text<br>",3);
fontWrap("yet more body text<br>",3);
?>
</body>
</html>
Setting Default Values for Arguments
• We really only need to change the font size
occasionally. Most of the time we use the
default value of 3.
• By assigning a value to an argument variable
within the function definition’s parentheses,
we can make the $size argument optional.
• If the function call doesn’t define an argument
for this, the value we have assigned to the
argument is used instead.
Setting Default Values for Arguments
• Ex: A Function with an Optional Argument
<head>
<title>Listing 6.10</title>
</head>
<body>
<?php
function fontWrap($txt, $size=3) {
echo "<font size=\"$size\"
face=\"Helvetica, Arial, Sans-Serif\">
Setting Default Values for Arguments
$txt</font>";
}
fontWrap("A heading<br>",5);
fontWrap("some body text<br>");
fontWrap("some more body text<br>");
fontWrap("yet more body text<br>");
?>
</body>
</html>
Setting Default Values for Arguments
• When the fontWrap() function is called with a
second argument, this value is used to set the
size attribute of the font element.
• When we omit this argument, the default value
of 3 is used instead. You can create as many
optional arguments as you want, but when
you’ve given an argument a default value, all
subsequent arguments should also be given
defaults.
Passing Variable References to Functions

• When you pass arguments to functions, they


are stored as copies in parameter variables.
Any changes made to these variables in the
body of the function are local to that function
and are not reflected beyond it.
• Ex: Passing an Argument to a Function by Value
<html>
<head>
<title>Listing 6.12</title>
</head>
Passing Variable References to Functions

<body>
<?php
function addFive($num) {
$num += 5;
}
$orignum = 10;
addFive($orignum);
echo $orignum;
?>
</body>
</html>
Passing Variable References to Functions
• The addFive() function accepts a single numeric
value and adds 5 to it. It returns nothing. We
assign a value to a variable $orignum and then
pass this variable to addFive().
• A copy of the contents of $orignum is stored in
the variable $num. Although we increment $num
by 5, this has no effect on the value of $orignum.
When we print $orignum, we find that its value is
still 10.
• By default, variables passed to functions are
passed by value. In other words, local copies of
the values of the variables are made.
Passing Variable References to Functions
• We can change this behavior by creating a
reference to our original variable.
• When you pass an argument to a function by
reference the contents of the variable you pass
($orignum) are accessed by the argument variable
and manipulated within the function, rather than
just a copy of the variable’s value (10).
• Any changes made to an argument in these cases
will change the value of the original variable. You
can pass an argument by reference by adding an
ampersand to the argument name in the function
definition.
Passing Variable References to Functions

• Ex: Using a Function Definition to Pass an


Argument to a Function by Reference
<html>
<head>
<title>Listing 6.12</title>
</head>
<body>
<?php
function addFive(&$num) {
$num += 5;
Passing Variable References to Functions

}
$orignum = 10;
addFive($orignum);
echo $orignum;
?>
</body>
</html>
Testing for the Existence of a Function
• We do not always know that a function exists
before we try to invoke it. Different builds of
the PHP engine may include different
functionality, and if you are writing a script that
may be run on multiple servers, you might
want to verify that key features are available.
• You can use function_exists() to check for the
availability of a function. function_exists()
requires a string representing a function name.
It will return true if the function can be located
and false otherwise.
Testing for the Existence of a Function
• Ex: Testing for a Function’s Existence
<html>
<head>
<title>Listing 6.14</title>
</head>
<body>
<?php
function tagWrap($tag, $txt, $func = “”) {
Testing for the Existence of a Function
if ((!empty($txt)) && (function_exists($func))) {
$txt = $func($txt);
return “<$tag>$txt</$tag>\n”;
}
}
function underline($txt) {
return “<u>$txt</u>”;
}
echo tagWrap(‘b’, ‘make me bold’);
// will print <b>make me bold</b>
Testing for the Existence of a Function
echo tagWrap(‘i’, ‘underline me too’, “underline”);
// will print <i><u>underline me too</u></i>
echo tagWrap(‘i’, ‘make me italic and quote me’,
create_function(‘$txt’, ‘return “&quot;
$txt&quot;”;’));
// will print <i>&quot;make me italic and quote
me&quot;</i>
?>
</body>
</html>
Testing for the Existence of a Function
• We define two functions, tagWrap() and
underline(). The tagWrap() function accepts
three strings: a tag, the text to be formatted,
and an optional function name. underline()
requires a single argument—the text to be
formatted.
• When we first call tagWrap() we pass it the
character b and the string bold. Because we
haven’t passed a value for the function
argument, the default value (an empty string)
is used.
Testing for the Existence of a Function
• We check whether the $func variable contains
characters and, if it is not empty, we call
function_exists() to check for a function by that
name. Of course, the $func variable is empty, so
we wrap the $txt variable and return the result.
• We call tagWrap() with the string ‘i’, some text,
and a third argument: “underline”.
function_exists() finds a function called
underline() so it calls this function and passes the
$txt argument variable to it before any further
formatting is done. The result is an italicized,
underlined string.
Testing for the Existence of a Function
• We call tagWrap(), which wraps text in
quotation entities. Of course, it would be
quicker to simply add the entities to the text to
be transformed.
• This illustrates the point that function_exists()
works as well on anonymous functions as it
does on strings representing function names.

You might also like