If you like SEOmastering Forum, you can support it by - BTC: bc1qppjcl3c2cyjazy6lepmrv3fh6ke9mxs7zpfky0 , TRC20 and more...

 

Creating Reusable Code (Functions) in PHP

Started by chinmay.sahoo, 12-28-2015, 02:16:17

Previous topic - Next topic

chinmay.sahooTopic starter

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:


Quoteecho '<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:

Quoteadd_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:

Quotefunction functionname()
{
block of statements;
return;
}

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

Quotefunction 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;
}



If you like SEOmastering Forum, you can support it by - BTC: bc1qppjcl3c2cyjazy6lepmrv3fh6ke9mxs7zpfky0 , TRC20 and more...