Download as pdf or txt
Download as pdf or txt
You are on page 1of 12

PHP Functions

What is a Function?

• PHP function is a piece of code that can be reused many times. It can take input as
argument list and return value. There are thousands of built-in functions in PHP.
• In PHP, we can define Conditional function, Function within Function and
Recursive function also.

Advantage of PHP Functions

• Code Reusability: PHP functions are defined only once and can be invoked many
times, like in other programming languages.
• Less Code: It saves a lot of code because you don't need to write the logic many
times. By the use of function, you can write the logic only once and reuse it.
• Easy to understand: PHP functions separate the programming logic. So, it is easier
to understand the flow of the application because every logic is divided in the form of
functions.

PHP User-defined Functions

We can declare and call user-defined functions easily. Let's see the syntax to declare user-
defined functions.

Syntax
function functionname(){
//code to be executed
}
Note: Function name must be start with letter and underscore only like other labels in
PHP. It can't be start with numbers or special symbols.

function1.php output:

1. <?php
2. function sayHello(){
3. echo "Hello PHP Function";
4. }
5. sayHello();//calling function
6. ?>

PHP Function Arguments

• We can pass the information in PHP function through arguments which is separated
by comma.
• PHP supports Call by Value (default), Call by Reference, Default argument
values and Variable-length argument list.
• Let's see the example to pass single argument in PHP function.

1
function_arg.php output:

<?php
function sayHello($name){
echo "Hello $name<br/>";
}
sayHello("Jose");
sayHello("Rizal");
sayHello("RTU");
?>

• Example to pass two argument in PHP function.

function_arg2.php output:

<?php
function sayHello($name,$age){
echo "Hello $name, you are
$age years old<br/>";
}
sayHello("Meghan",27);
sayHello("Angelina",29);
sayHello("Johnny",23);
?>

PHP Call By Reference

• Value passed to the function doesn't modify the actual value by default (call by value).
But we can do so, by passing value as a reference.
• By default, value passed to the function is call by value. To pass value as a reference,
you need to use ampersand (&) symbol before the argument name.
• Let's see a simple example of call by reference in PHP.

function_ref.php output:

<?php
function adder(&$str2)
{
$str2.='Call By Reference';
}
$str = 'Hello ';
adder($str);
echo $str;
?>

PHP Function: Default Argument Value

• We can specify a default argument value in function. While calling PHP function if you
don't specify any argument, it will take the default argument.
• Let's see a simple example of using default argument value in PHP function.

2
function_default.php output:


<?php
function

sayHello($name="Jose"){

echo "Hello $name<br/>";

}

sayHello("Rizal");
sayHello();//passing no value
sayHello("John");
?>

PHP Function: Returning Value

Example of PHP function that returns value.

return_function.php output:


<?php
function
• cube($n){
return
• $n*$n*$n;
}

echo "Cube of 3 is: ".cube(3);
?>•

PHP Variable Scope

• There's a thing called scope in programming. This refers to where in your scripts a
variable can be seen.
• If a variable can be seen from anywhere, it's said to have global scope. In PHP,
variables inside of functions can't be seen from outside of the function. And functions
can't see variables if they are not part of the function itself. Try this variation of our
script as an example:

<?PHP
$error_text = "Error Detected";
display_error_message();
function display_error_message() {
print $error_text;
}
?>

• This time, set up a variable called $error_text to hold the text of our error message.
This is set up outside of the function. Run the script, and you'll get a PHP error
message about " Undefined variable".
• Likewise, try this script:

<?PHP
display_error_message();
print $error_text;

3
function display_error_message() {
$error_text = "Error message";
}
?>

• This time, the variable is inside the function, but we're trying to print it from outside the
function. You still get an error message. Here's a correct version:

<?PHP
display_error_message();
function display_error_message() {
$error_text = "Error message";
print $error_text;
}
?>

Output:

• Here, both the variable and the print statement set up inside of the function. The error
message now prints.
• If you need to examine what is inside of a variable, you need a way to get the variable
to the function. That's where arguments come in.

Summary:

➢ To pass something to a function, create an argument


➢ To call a function that has an argument, don't leave the round brackets empty

Check for blank Textboxes with PHP


• Check that the textbox doesn't just contain this " ". There has to be something in it, like
"Bill Gates". Here's a script that does all three items on our list:

<?PHP
$user_text = trim("Bill Gates");
display_error_message($user_text);
function display_error_message($user_text) {
if ($user_text == " ") {
print "Blank text box detected";
}
else {
print "Text OK";
}
}
?>

4
Output:

• Try it out. When you run the script, you should find that Text OK prints. Now change
this line:

$user_text = trim("Bill Gates");

to this:
$user_text = trim("");

blank_text_bill2.php

<?PHP
$user_text = trim("");
display_error_message($user_text);

function display_error_message($user_text) {
if ($user_text == "") {
print "Blank text box detected";
}
else {
print "Text OK";
}
}
?>

Output:

• Run your script again. This time, Blank text box detected should print out.
• No text from a textbox on a form, but just simulating the process. If you want to try out
a version with all the HTML, here it is.

5
formFunction.php
<html>
<head>
<title>Check For Blank Text Boxes</title>
</head>
<body>
<?php
$first ="";
$second = "";
function display_error_message($user_text) {
if ($user_text == "") {
print "One or more blank text boxes detected<br>";
}
else {
print "Text boxes OK<br>";
}
}
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$first = trim($_POST['first']);
$second = trim($_POST['second']);
display_error_message($first);
display_error_message($second);
}
?>
</body>
<FORM Method = "POST" action ="formFunction.php">
First Name: <INPUT TYPE = "text" name = "first" value ="<?=$first?>">
Surname: <INPUT TYPE = "text" name = "second" value ="<?=$second?>">
<input type="submit" name="Submit" value="Submit">
</FORM>
</html>

Output:

6
PHP Server Variables

• PHP stores a list of information about the server. This will include things like, the
browser the visitor is using, the IP address, and which web page the visitor came from.
Here's a script to try with those three Server Variables:

$referrer = $_SERVER['HTTP_REFERER'];
$browser = $_SERVER['HTTP_USER_AGENT'];
$ipAddress = $_SERVER['REMOTE_ADDR'];
print "Referrer= ". $referrer. "<BR>";
print "Browser= ". $browser. "<BR>";
print "IP Adress= ". $ipAddress;

• These are useful if you want to log your stats, or to ban a particular IP address! (If you
run the script on a local machine, you may get an error for the referrer.)
• So to get at the values in Server Variables, the syntax is this:

$_SERVER['Server_Variable']

Output:

• You start with a dollar sign, then an underscore character ( $_ ). Then you add the
word SERVER. In between square brackets, you type the name of the server variable
you want to access. Surround this with either single or double quotes.
• Because you are returning a value, you need to put all that on the right hand side of
an equals sign. On the left of the equals sign ( = ), you need a variable to hold the
string that is returned.
• The server variables are held in an array (associative), so you can use a foreach loop
to get a list of all available ones. Try this script:

<?PHP
foreach($_SERVER as $key_name => $key_value) {
print $key_name. " = " . $key_value. "<br>";
}
?>

7
Output:

• What the script does is to loop round all the server variables and print out the keys and
values in the SERVER array.

PHP Header Function

• When you request a web page be brought back to your browser, you're not just bringing
back the web page. You're also bringing back something called a HTTP HEADER.
• This is some extra information, such as type of program making the request, date
requested, should it be displayed as a HTML document, how long the document is,
and a lot more besides.
• One of the things HTTP HEADER also does is to give status information. This could
be whether the page was found (404 errors), and the location of the document. If you
want to redirect your users to another page, here's an example:
<?PHP
header("Location: http://www.rtu.edu.ph/");
?>
<html>
<body>
</body>
</html>

• Note how the header code goes before any HTML. If you put header code after the
HTML, you'll get an error along the lines of "Cannot modify header information."

The PHP INCLUDE Function

• Being able to include other files into your HTML code, or for your PHP scripts, is a
useful thing. The include( ) function allows you do this.
• Suppose you have a text file that you want to include in a web page that you've already
got up and running. You could copy and paste the text from the file straight into you
HTML. Or you could use the include() function.
• Now take a look at the code for this page:

8
include.php textfile.txt

<html> Mary had a little one. It's


<HEAD> hair was white as snow.
<TITLE>Include files</TITLE>
</HEAD>

<body>
<H3>Normal text here </H3>
Normal text written in a HTML
Editor

<H3>Include File here</H3>


<?PHP include "textfile.txt" ; ?>
</body>
</html>

Output:

• Our PHP code, here it is:

<?PHP
include "textfile.txt";
?>

• So in between PHP script tags, type the word include. After the word include, type the
name of the file you want to include on your page. Your filename can either go after a
space, and between quotation marks, or you can put it in round brackets (again, with
the quotes).
• As well as including text, you can include HTML. This can save you lots of work. For
example, a web page typically contains a menu bar, with links to other areas of your
site. Something like this:

9
links.php linksPage.txt
<html> <table width="182" border="1"
<head> cellpadding="0" cellspacing="0">
<title>Menu Bar Include</title> <tr>
<meta http-equiv="Content-Type" <td width="182" height="30"
content="text/html; charset=iso- valign="middle" bgcolor="#FFFFCC"><a
href="links.php">About
8859-1"> Us</a></td></tr>
</head> <tr><td valign="middle" height="30"
<body bgcolor="#FFFFFF" bgcolor="#FFFFCC"><a
text="#000000"> href="links.php">Latest
<?PHP include "linksPage.txt" ?> News</a></td></tr><tr>
</body> <td height="30" valign="middle"
</html> bgcolor="#FFFFCC"><a
href="links.php">Forum</a></td>
</tr><tr>
<td height="30" valign="middle"
bgcolor="#FFFFCC"><a
href="links.php">Login</a></td>
</tr>
</table>

Output:

Suppose you decide to add a new section to your site. The new page should be like this:

links.php linksPage.txt
<html> <table width="182" border="1"
<head> cellpadding="0" cellspacing="0">
<title>Menu Bar <tr>
<td width="182" height="30"
Include</title>
valign="middle" bgcolor="#FFFFCC"><a
<meta http-equiv="Content- href="links.php">About
Type" content="text/html; Us</a></td></tr>
charset=iso-8859-1"> <tr><td valign="middle" height="30"
</head> bgcolor="#FFFFCC"><a
<body bgcolor="#FFFFFF" href="links.php">Latest
text="#000000"> News</a></td></tr><tr>
<?PHP include <td height="30" valign="middle"
"linksPage.txt" ?> bgcolor="#FFFFCC"><a
href="links.php">Forum</a></td>
</body>
</tr><tr>
</html> <td height="30" valign="middle"
bgcolor="#FFFFCC"><a
href="links.php">Login</a></td>
</tr>
<tr>
<td height="30" valign="middle"
bgcolor="#FFFFCC"><a href="links.php">New
Section</a></td>
</tr>
</table>

10
Output:

• If your site contains lots of pages, that would mean having to amend the HTML of all
of them. Instead, use the include() function.
• To see how it works, load up the page called links.php, you should see the first menu
bar. This has the include line, that points to another file - linksPage.txt.
• If you open up the text file called linksPage.txt, you'll see that it's just a HTML table. To
get this table into the PHP page called links.php, add this:

<?PHP include "linksPage.txt" ?>

• The point is, the include line on all pages of out site, and to add a new section, just
change the text file linksPage.txt. This change would then mean that all the pages in
the site would be updated.
• Add the following line to the page called linksPage.txt. Put it between the TABLE tags:

<TR>
<TD height="30" valign="middle" bgcolor="#FFFFCC">
<a href="links.php">New Section</a>
</TD>
</TR>

• Save the page, and then load up links.php again. You should see a new section
added to your menu bar.

Including Scripts

• You can also use the include() function for scripts. You could include those valuable
error checking functions that you've stored in one PHP file. Or just use it to cut down
on the amount of code in the page.
• The script uses include to include another PHP script - myOtherScript.php. The
function called doPrint() is in myOtherScript.php.
• Load up the page called includeScript.php in your browser. You should see
two lines printed out.
• include is a very useful function – one of the most useful inbuilt PHP functions.

11
includeScript.php myOtherScript.php

<?PHP <?PHP
include "myOtherScript.php";
function doPrint() {
print "This was printed from
the includeScript.php"; print "This was printed from the
print "<BR>"; myOtherScript.php";
doPrint(); }
?>
?>

Output:

12

You might also like