Sunday, November 7, 2010

Basic PHP knowledge for Drupal - Part 3

2. Functions in PHP: Functions are a block of code where operations and functionalities are defined in one place and called from another place. Thus one can perform a task without writing the same code again. Every function returns a value, it may be an integer, string or boolean etc. Functions must be defined in the included files or scripts to use them. Here goes an example of simple functions which takes 3 numbers, first two numbers are added and then multiplied with the third number.

Function definition:
function foo($a,$b,$c){
$result = ($a+$b) * $c;
return $result;
}

Here $a,$b,$c are called argument signatures. they are just the replica of the parameter which is put as the argument during function call. Functions can be called by value or called by reference. In case of call by reference, function does not need to return anything as in this case modification occurs inside the passed variables (argument).



Function Usage:
echo foo(1,2,3);

The output would be 9.

echo foo(3,2,3);
The output would be 15.


Though there are lot of functions and more complex in nature defined in Drupal API. Don't worry, you don't have to remember all the function names. By doing drupal projects you will automatically remember those useful function names. For other unknown functions, just go to api.drupal.org to get the documentation of all the defined function in Drupal API.

For more reference about PHP functions read this link.