Posts Tagged ‘functions’

We have been using the print and echo statements in our previous posts right? We know these two are used to print. But what are they actually? These are in-built functions. When we include a print statement in our script, we are actually “calling” the in-built function print. Similarly, a user can define his/her own functions, called user-defined functions.

Functions are the block of statements that can be used repeatedly in a script. These lines will be executed only upon a¬† “call” to the function.

User defined function :

Function declaration starts with the keyword “function” followed by function name. A function name can start with a letter or underscore and are case-insensitive.

Syntax :

function functionName() {
//code to be executed
}

1. Simple php function.
Lets write a simple php function.


<?php
//simple function.
function printMessage() {
echo "Ahoy!!";
}

printMessage(); // call the function.
?>

2. Function with arguments.

Arguments are like variables. Their scope is limited only to that particular function to which they have been passed. Passing the arguments is nothing but passing the information. Arguments are specified after the function name, inside the parentheses. A number of arguments can be passed each one separated  by a comma. The following example illustrates the function with a single argument.


<?php
//function with arguments.
function printMessageArg1($name) {
echo "$name";
}

printMessageArg1("Adonis"); // call the function.
?>

3. Function with default arguments value.

You can give your arguments a default value, like so :


<?php
//function with default arguments value.
function printMessageArg2($age=20) {
echo "your age is $age";
}

printMessageArg2(30); // call the function.
echo "<br>";
printMessageArg2(); // call the function. No value is passed, hence will take the default value specified.
?>

4. Function with return values.

You can make your function pass some information to the called function, using the keyword “return“. This value is called return value. The following function computes the sum of two numbers and returns the same to the called function :


<?php
//function with return values.
function retSum($x=0,$y=0) {
$z=$x+$y;
return $z;
}

$a=retSum(2,3); // call the function.
echo "$a<br>";
$a=retSum(3.57,66.3344); // call the function.
echo "$a<br>";
$a=retSum(); // call the function.
echo "$a<br>";
?>

Advertisements