Functions In PHP

Functions in PHP

  In this example, PHP codes are embedded in HTML. Here, we have used a function ‘DisplayTitle()’. This function starts with the word function and indicates that the character inserted just after this word is a function. It displays  the title of the tutorial. Any one who will go through this will understand the purpose of this function from its name.   Look at a more complex example: Example:
<?php

$makingfoo = true;

/* Here we should note that we can’t call foo() from here  as it doesn’t exist yet, but we can call bar() */

bar();

if ($makingfoo) {

function foo (){

echo “This does not exist unless and until the

program execution reaches here.\n”;

}

}

/* Here we can safely call foo()

since $makingfoo calculated to true */

if ($makingfoo) foo();

function bar()

{

echo “This does exist immediately upon the starting of the program.\n”;

}

?>
 

4.1 User defined function

Let’s see how a user can define a function according to his need. Look at the syntax of the user defined function:   function my_function($arg1,$arg2){ //statements are inserted here }   FUNCTIONS IN PHP Here is a syntax of a user defined function. Simply function succeeded by function name and the arguments inside parenthesis which are completely optional. Assume you want to create a function that randomly produces a password. Let this function be randompassword(). A function cannot be completed without the use of opening and closing parentheses () and the opening and closing braces {}. Example:
<?php

function randompassword()

$characters = “abcdefghijklmnopqrstuvwxyz123456789”;

$password = ‘’;

for($i=0;$i<7;$i++) {

$password .= $characters{rand() % 40};

}

 return $password;

}

//this is to use the function

$password = randompassword();

?>
Here, this function creates a random password that includes both letters and numbers. Letters and passwords are inserted in the $characters variable. The randompassword() function is used here for making the password random. The $password variable returns a specific result. At last, the ‘$password=randompassword()’ function is used to run it.  

4.2 Function scope

The origin from where a function can be accessed is called the function scope. A function, once declared, can be accessed from any section of a program. A variable scope will be local to a function, if defined within a function. Use the global key word while using a variable defined in the body part of the program. Example:
<?php

function MathSum (){
global $sum = 4 + 4;
}

$sum = 0

MathSum ()

print “4 + 4 = “.$sum

?>
  Here, the global keyword instructs PHP to look for a variable defined outside the function.  

4.3 Function arguments and return values

  In PHP, the codes are passed by both objects and arrays. We have two models to pass data in a program: ‘Pass by value’ and ‘Pass by reference’.

Pass by value:

This indicates passing the variables. Here the variables are sent as an argument to a defined function. The assignment operator is used to assign it to a different variable. The receiving function or the variable gets a copy of the value of the variable.   Look at the codes below: $x=5; $y=$x; Here, both the variables are assigned the value 5. You can change either of these two variables, but the other one will not be affected. The modification that we insert here, are completely local to the function it belongs to. These changes are not reflected outside the function. Example:
<html>

<head>

<title>Passing an Argument tutorial</title>

</head>

<body>

<?php

function addFour( $num ) {

$num += 4;

}

$originalnum = 40;

addFour( $originalnum );

print( $originalnum );

?>

</body>

</html>
The output of this program is as follows: 40  

Pass by Reference:

‘Pass by Reference’ is a unique feature of OOPs (Object Oriented Programming languages). It creates a new indicator but indicates to the same variable. As the ‘Pass by Value’ creates a copy of a variable,the ‘Pass by Reference’ creates a different name of the same variable. The ampersand sign (&) is used while passing by reference.It is always inserted just after an assignment operator.   Look at the code below: $x =& $y;   Here, the ampersand operator is used to create a reference to the variable $y. Look how this code is executed: $x = (& $y);   In order to define arguments to pass to a function, we need to insert a list of names. These names must be inserted within parentheses in the statements of the function. Look at the code below: function Passfunction ($argument1, $argument2)  

Returning results from a function:

In PHP, a function returns a specific result when a code is called. Here the ‘return’ keyword is used. Look at the following syntax: return $abc; While processing a return statement, the function is terminated. Here the value of the variable $abc is returned to a code that is called. The values must be specified in the variable. Using one return statement, a single variable can be returned. We must define an array in case of returning more than one variable. Look at the example below:
<html>

<head>

<title>Returning Result from a Function </title>

</head>

<body>

<h1>Display capacity</h1>

<br />

<?php

function CalCapacity ($a, $b, $c)

{

$capacity = $a * $b * $c;

return $capacity;

}

$length = 4;

$width = 5;

$hight = 6;

print “The capacity of the object is “ .

CalCapacity($length, $width, $hight) . “ capacity units.”;

?>

</body>

</html>
  In the above example, a number of variables are passed to a function as an argument. Here a result is returned. We are now defining a function ‘CalCapacity’. It receives parameters like $a, $b and $c. The function CalCapacity($a,$b,$c) will calculate and determine the capacity of an object. The function will return the result in the code that is called. The variables $length, $width and $height include three values. The print statement will show the result. Look at another example for better understanding:
<?php

function mySum($numA, $numB) {
 $total = $numA + $numB;
 return $total;
}

$numericValue = 0;

echo “First numericValue = “. $numericValue .” <br />”;

$numericValue = mySum(3, 4);

echo “Second numericValue = “ . $numericValue.”<br />”;

?>

The output of this program is:

First numericValue = 0

Second numericValue = 7
 

4.4 Internal function

To ease the development process, PHP provides a large number of in-built functions some standard as a part of core php and some shipped with some specific extensions. These functions that require specific PHP extensions compiled in, otherwise fatal “undefined function” errors will appear. For example, to use image functions such as imagecreatetruecolor(), PHP must be compiled with GDsupport. Or, to use mysql_connect(), PHP must be compiled with MySQL support. On windows these extensions have to be loaded by specifying their dll location example: extension=php_gd2.dll in the php.ini file. Here are some of these Internal Functions: imagecreatetruecolor() The ‘imagecreatetruecolor()’ function returns an image identifier that represents a black image of the specified size. It returns an image resource identifier if it is successfully executed. The ‘FALSE’ value is returned if an error occurs. Example:
<?php

header (“Content-type: image/png”);

$im = @imagecreatetruecolor(120, 20) or die(“Cannot Initialize new GD image stream”);

$text_color = imagecolorallocate($im, 233,14,91);

imagestring($im, 1, 5, 5, “A Simple Text String”, $text_color);

imagepng($im);

imagedestroy($im);

?>
mysql_connect() The ‘mysql_connect()’ function is used to connect to a MySQL Database Server. It returns a MySQL link identifier if it is successfully executed. A ‘FALSE’ value is returned if an error occurs while executing the program. Look at the examples below:
<?php

$con = mysql_connect(‘localhost’,’root’, ‘mysql_password’);

if (!$con) {

die(‘Could not connect: ‘ . mysql_error());

}

echo ‘Connected successfully’;

mysql_close($con);

?>
  phpinfo() The phinfo() function is extremely helpful for new users. We can get a lot of information on PHP by using this function. We can get the information on the current state of PHP as the output. It returns ’TRUE’ if the function is executed successfully. It returns ‘FALSE’ if an error occurs while the execution of the program.  

4.5 Static variables

PHP provides some Static variables which exist only in a local function scope. The Static variables do not loose their value in case the function (where they are declared) execution is terminated and is recalled later. Static variables can be used for working with recursive functions, where a function calls itself. Example 1:
<?php

$abc = 9;

function fruit () {

static $abc = 0;

$fruit_arr =

array(“mango”,”apple”,”guava”,”bananna”);

$abc++;

$abc %= count($fruit_arr);

return $fruit_arr[$abc];

}

for ($j=0; $j<10; $j++) {

print “What’s for dinner - “.fruit().”?<br />”;

}

print $abc; # Just to show you this is a different abc!

?>
The output of this program is: Which fruit you like – apple? Which fruit you like – guava? Which fruit you like – bananna? Which fruit you like – mango? Which fruit you like – apple? Which fruit you like – guava? Which fruit you like – bananna? Which fruit you like – mango? Which fruit you like – apple? Which fruit you like – guava?   Example 2:
<?php

            function &quick_ref() {

                        static $static_obj;

                        echo “We are using Static object: “;

                        var_dump($static_obj);

                        if (!isset($static_obj)) {

                                    // Assign a reference to the static variable

                                    $static_obj = &new stdClass;

                        }

                        $static_obj->property++;

                        return $static_obj;

            }

            function &quick_noref() {

                        static $static_obj;

                        echo “ We are using Static object: “;

                        var_dump($static_obj);

                        if (!isset($static_obj)) {

                                    // Assign the object to the static variable

                                    $static_obj = new stdClass;

                        }

                        $static_obj->property++;

            return $static_obj;

            }

            $static_obj1 = quick_ref();

            $still_static_obj1 = quick_ref();

            echo “\n”;

            $static_obj2 = quick_noref();

            $still_static_obj2 = quick_noref();

?>
The output of this program is as follows: We are using Static object: NULL We are using Static object: NULL We are using Static object: NULL We are using Static object: object(stdClass)#3 (1) { [“property”]=> int(1) }