PHP Functions: What is the importance of functions in PHP

· Dev & Design
Authors

Function play a very important role in any programming language, including PHP.
They are pieces of code which takes in some value processes it and produce results.

Funtions are very useful when you are writing repetitive code, and you are in need
of same code in some other script.


Function with no Arguments:

For a funtion to process on require some arguments to be passed to it.
This is not the case always, some funtions require no arguments.
such funtion outputs the same message whenever it is called on.
This is illustrated in the example below.

function display_goodbye_message() //no semicolon here!
{
print �<h1>Thanks for visiting our web-site</h1>�;
}

Whenever this function is called on, it outputs the same message.
It takes no arguments and doesn’t return anything.


Function to Perform Calculation

The “return” statement is used to send the result to the function. Here in
this case the result is calculated value of the purchase (which is number
of items purchased multiplied by price)

function calculate_value($price, $items)
{
return ($price * $items); //returns a result
}


Calling a Function Dynamically

A function can be called dynamically in the same way we access dynamic variables.
We can treat an expression’s name as a funtion name and thus can call it.

$function_name = �calculate_value�;
$function_name(40, 5);

This is identical to:
calculate_value(40, 5);


Global statement in a Function.

When we want to access some important information which are outside the function,
and without using arguments. Then we have to use the “global” statement.

<html>
<body>
<?php
function add($x,$y)
{
global $exchange_rate;
$total = $x + $y + $exchange_rate;;
return $total;
}echo “1 + 16 = ” . add(1,16)
?>
</body>
</html>

Here we have used the global statement to tell the function that “$exchange_rate”
is declared outside the the function. If we wont declare like this then the function
would have returned zero, since $exchange_ratewould have been “NULL”.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s