phpwithmysql2.1

 

Unit-II

Functions

What Is a Function?

A function —is a self - contained block of code that performs a specific task. It is also called a subroutine in some other languages.

A function often accepts one or more arguments , which are values passed to the function by the code that calls it. The function can then read and work on those arguments.

 A function may also optionally return a value that can then be read by the calling code. In this way, the calling code can communicate with the function.

 

Why Functions Are Useful

1.      They avoid duplicating code

2.      They make it easier to eliminate errors

3.      Functions can be reused in other scripts

4.      Functions help you break down a big project

 

Calling Functions

To call a function, you write the function name, followed by an opening and a closing parenthesis and If you can also  pass arguments to the function:

functionName(argument1, argument2 )

 

If a function returns a value, you can assign the value to a variable:

$returnVal = functionName( argument );

 

You can also pass the return value directly to another function, such as print() :

print( functionName( argument ) );

 

<html>

<head>

<title> Square roots < /title >

<link rel=”stylesheet” type=”text/css” href=”common.css” />

</head>

<body>

<h1> Square roots </h1>

<?php

echo “The square root of 9 is: “ . sqrt( 9 ) . “. <br/> ”;

echo “All done! <br/> ”;

?>

</body>

</html>

Ouput:

Square roots

The square root of 9 is:3


Working with Variable Functions

Sometimes it ’ s useful to be able to store the name of a function in a string variable, and use that variable instead of the function name when calling a function.

 

Example:

$squareRoot = “sqrt”;

echo “The square root of 9 is: “ . $squareRoot( 9 ) . “. < br/ > ”;

echo “All done! < br/ > ”;

 

Writing Your Own Functions

Defining a function is really easy — just use the following syntax:

 

function myFunc()

{

// (do stuff here)

}

 

Example

function hello()

{

echo “Hello, world! <br/> ”;

}

 

hello();            // Displays “Hello, world!”

 

Defining Parameters

A parameter is a variable that holds the value passed to it when the function is called. You can  specify one or more corresponding parameters when you define your function.

 

function myFunc( $oneParameter, $anotherParameter )

{

// (do stuff here)

}

 

<html>

<head>

<title> Saying hello with style </title>

<link rel=”stylesheet” type=”text/css” href=”common.css”/>

</head>

<body>

<h1 > Saying hello with style < /h1 >

<?php

function helloWithStyle( $font, $size )

{

echo “ <p style=\”font-family: $font; font-size: {$size}em;\”> Hello, world! </p> ”;

}

helloWithStyle( “Helvetica”, 2 );

helloWithStyle( “Times”, 3 );

helloWithStyle( “Courier”, 1.5 );

?>

</body>

</html>

 

Optional Parameters and Default Values

PHP lets you create functions with optional parameters. You define an optional parameter

as follows:

function myFunc( $parameterName=defaultValue )

{

// (do stuff here)

}

 

<?php

function helloWithStyle( $font, $size=1.5 )

{

echo “ <p style=\”font-family: $font; font-size: {$size}em;\”> Hello, world! </p> ”;

}

helloWithStyle( “Helvetica”, 2 );

helloWithStyle( “Times”, 3 );

helloWithStyle( “Courier” );

?>

 





Returning Values from Your Functions

To get your function to return a value, use PHP ’ s return statement:

function myFunc()

 {

// (do stuff here)

return value;

}

value can be any expression, so you can use a literal value (such as 1 or false ), a variable name (such as $result ), or a more complex expression .

<?php

function makeBold( $text )

{

return “ <b> $text </b> ”;

}

$normalText = “This is normal text.”;

$boldText = makeBold( “This is bold text.” );

echo “ <p> $normalText </p> ”;

echo “ <p> $boldText </p> ”;

?>

 





Understanding Variable Scope

local variables:

The important thing to remember is that any variables created within a function are not accessible outside the function. The variables $hello and $world that are defined inside the function are not available to the calling code. The scope of $hello and $world is said to be limited to the function that created them; they are said to be local variables .

<?php

function helloWithVariables()

{

$hello = “Hello, “;

$world = “world!”;

return $hello . $world;

}

echo helloWithVariables() . “ <br/> ”;

echo “The value of \$hello is: ‘$hello’ <br/> ”;

echo “The value of \$world is: ‘$world’ <br/> ”;

?>


Working with Global Variables

A variable that can be accessed anywhere in your script, whether inside or outside a function. Such a variable is called a global variable .

To use such a variable inside a function, write the word global followed by the variable name inside the function ’ s code block. Here ’ s an example:

 

$myGlobal = “Hello there!”;

function hello()

{

global $myGlobal;

echo “$myGlobal <br/> ”;

}

hello(); // Displays “Hello there!”

 

Using Static Variables to Preserve Values

Static variables

These types of variables are still local to a function, in the sense that they can be accessed only within the function ’ s code. Static variables remember their values from one function call to the next.

To declare a local variable as static, all you need to do is write the word static before the variable

name, and assign an initial value to the variable:

 

static $var = 0;

function nextNumber()

{

static $counter = 0;

return ++$counter;

}

echo “I’ve counted to: “ . nextNumber() . “ < br/> ”;

echo “I’ve counted to: “ . nextNumber() . “ < br/> ”;

echo “I’ve counted to: “ . nextNumber() . “ < br/> ”;

 

Now the code displays:

I’ve counted to: 1

I’ve counted to: 2

I’ve counted to: 3

 

Creating Anonymous Functions

PHP lets you create anonymous functions — that is, functions that have no name. You might want to create anonymous functions for two reasons:

·         To create functions dynamically

·         To create short- term, disposable functions

To create an anonymous function, you use create_function() .

This expects two arguments: a comma - separated list of parameters (if any),

and the code for the function body .

It returns a unique, randomly generated string value that you can use to refer to the function later:

 

$myFunction = create_function( ‘$param1, $param2’, ‘function code here;’ );

           

$mode = “+”;

$processNumbers = create_function(‘$a, $b’, “return \$a $mode \$b;”);

echo $processNumbers(2, 3);                                 // Displays “5”

 

Working with References

When you create a reference to a PHP variable, you now have two ways to read or change the variable ’ s contents — you can use the variable name, or you can use the reference.

 

PHP Call By Value In case of PHP call by value, actual value is not modified if it is modified inside the function.

Let's understand the concept of call by value by the help of examples. In this example, variable $str is passed to the adder function where it is concatenated with 'Call By Value' string. But, printing $str variable results 'Hello' only. It is because changes are done in the local variable $str2 only. It doesn't reflect to $str variable.

 

<?php

function adder($str2)

{

$str2 .= 'Call By Value';

}

$str = 'Hello ';

adder($str);

echo $str;

?>

 

Output:

Hello

 

Passing References to Your Own Functions(Call By Reference)

By passing a reference to a variable as an argument to a function, rather than the variable itself, you pass the argument by reference , rather than by value. This means that the function can now alter the original value, rather than working on a copy.

 

To get a function to accept an argument as a reference rather than a value, put an ampersand (&) before the parameter name within the function definition:

function myFunc(&$aReference )

{

// (do stuff with $aReference)

}

Now, whenever a variable is passed to myFunc() , PHP actually passes a reference to that variable, so that myFunc() can work directly with the original contents of the variable, rather than a copy.

 

Example

function resetCounter(& $c)

{

$c = 0;

}

$counter = 0;

$counter++;

$counter++;

$counter++;

echo “$counter <br/> ”;                 // Displays “3”

resetCounter( $counter );

echo “$counter <br/> ”;                 // Displays “0”

 

Returning References from Your Own Functions

You can also get functions to return references, rather than values. To do this, you place an ampersand before the function name in your function definition. Then, when you return a variable with the return statement, you pass a reference to that variable back to the calling code, rather than the variable ’ s value:

 

function &myFunc()

{

// (do stuff)

return $var;                                       // Returns a reference to $var

}          

 

Example:

$myNumber = 5;

function &getMyNumber()

{

global $myNumber;

return $myNumber;

}

$numberRef = &getMyNumber();

$numberRef++;

echo “\$myNumber = $myNumber<br/>”;    // Displays “6”

echo “\$numberRef = $numberRef<br/>”;         // Displays “6”

 

Writing Recursive Functions

Recursion occurs when a function calls itself. Such a process would repeat indefinitely if not stopped, so the recursion needs to have some sort of end condition — much like a loop. This end condition is known as the base case , and the part of the function that calls itself is known as the recursive case .

Here ’ s a quick overview of how a recursive function operates:

1.      The recursive function is called by the calling code

2.      If the base case, or end condition, is met, the function does any processing required, then exits

3.      Otherwise, the function does any processing required, then calls itself to continue the recursion.

<?php 

function fact ($n) 

{ 

    if($n <= 1)  

    { 

        return 1; 

    } 

    else  

    { 

        return $n * fact($n - 1); 

    } 

} 

echo "Factorial of 6 is " .fact(6); 

?> 

Next Topic Objects

No comments:

Post a Comment