Creating Reusable Code (Functions) in PHP

Author Topic: Creating Reusable Code (Functions) in PHP  (Read 800 times)

Offline chinmay.sahooTopic starter

  • Trade Count: (0)
  • Full Member
  • ***
  • Thank You 2
  • Posts: 159
  • Karma: 0
    • Hot Shaper
Creating Reusable Code (Functions) in PHP
« on: 12-28-2015, 00:16:17 »
Applications often perform the same task at different points in the script or in different scripts. This is when functions come in handy. A function is a group of PHP statements that perform a specific task. You can use the function wherever you need to perform the task.

For example, suppose you add a footer to the bottom of every Web page by using the following statements:


Quote
echo ‘<img src=”greenrule.jpg” width=”100%” height=”7” />
<address>My Great Company
<br />1234 Wonderful Rd.
<br />San Diego, CA 92126
</address></font>
<p>or send questions to
<a href=”mailto:sales@company.com”>sales </a>
<img src=”greenrule.jpg” width=”100%” height=”7” />’;

It’s not uncommon for Web pages to have headers or footers much longer than this. So, rather than type this code into the bottom of every Web page, probably incurring at least a couple of typos in the process, you can create a function that contains the preceding statements and name it add_footer. Then at the end of every page, you can just use the function (a process referred to as calling the function) that contains the footer statements. The code for this simple function call is as follows:

Quote
add_footer();

Notice the parentheses after the function name. These are required in a function call because they tell PHP that this is a function.

Defining functions

You can create a function by putting the code into a function block. The general format is as follows:

Quote
function functionname()
{
block of statements;
return;
}

For example, you create the function add_footer() that I discuss in the preceding section with the following statements:

Quote
function add_footer()
{
echo ‘<img src=”greenrule.jpg” width=”100%” height=”7” />
<address>My Great Company
<br />1234 Wonderful Rd.
<br />San Diego, CA 92126
</address></font>
<p>or send questions to
<a href=”mailto:sales@company.com”>sales </a>
<img src=”greenrule.jpg” width=”100%” height=”7” />’;
return;
}


 

Related Topics

  Subject / Started by Replies Last post
0 Replies
831 Views
Last post 05-09-2013, 06:55:45
by Sairch
1 Replies
1279 Views
Last post 03-30-2015, 03:51:18
by uditsh
0 Replies
1382 Views
Last post 12-24-2015, 00:40:20
by chinmay.sahoo
1 Replies
1788 Views
Last post 05-14-2016, 01:55:23
by TomClarke
1 Replies
1996 Views
Last post 05-14-2016, 02:20:24
by TomClarke