PHP FUNCTIONS

 PHP FUNCTIONS 

  • ·         A function is a code or statement block in a program.
  • ·         perform some specific tasks.
  • ·         Used repeatedly in a program.
  • ·         Not execute automatically when a page loads.
  • ·         Executed by a call to the function.
  • ·         Name must start with a letter or an underscore, and not be case-sensitive.
  • ·         Take information as the parameter, executes a block of statements, or perform operations on these parameters and returns the result.

 Uses of functions

·         Reusability: 

·         Easier error detection: 

·         Easily maintained: 

 Creating a function

While creating a user-defined function we need the following things:

1.    Any name ending with an open and closed parenthesis is a function.

2.    Name always begins with the keyword function.

3.    To call a function need its name followed by the parenthesis

4.    Name starts with an alphabet or underscores not any number, not case-sensitive.

 Function function_name(){

    executable code;

}

 Example:-

<?Php

  

Function f1() 

{

    echo "hello php";

}

  

// calling the function

F1();

  ?>

 Function parameters or arguments (function arguments)

  • ·         Parameters:-  the information or variable, within the function’s parenthesis.
  • ·         Hold the values during runtime.
  • ·         Use many parameters with a comma (,) operator.
  • ·         Parameters accept inputs during runtime.
  • ·         Passing the values during a function call called arguments.
  • ·         Information passed to functions through arguments. An argument is a value passed to a function as a variable and a parameter is used to hold those arguments.
  • ·         Arguments are specified after the function name, inside the parentheses.


syntax:

Function function_name($first_parameter, $second_parameter) {

    executable code;

}

Example:

<?Php

  

// function along with three parameters

Function add($num1, $num2, $num3) 

{

    $product = $num1 + $num2 + $num3;

    echo "the product is $product";

}

  // caling the function

// passing three arguments

Add(2, 3, 5);

  ?>

 

Php provides us with two major types of functions:

·         Built-in functions :

·         Provides a huge collection of built-in library functions.

·         Already coded and stored in form of functions.

·         To use just call them as per requirement like, var_dump, fopen (), print_r(), gettype() and so on.

·         User-defined functions :

·         Create our own customized functions.
Can create our own packages of code and use them when it needs by calling it.

 Php is a loosely typed language

  • ·         Automatically associates a data type to the variable, depending on its value.
  • ·         Not set in a strict sense, like adding a string to an integer without causing an error.
  • ·         In PHP 7, type declarations were added.
  • ·         Gives an option to specify the expected data type when declaring a function, and by adding the strict declaration, it will throw a "fatal error" if the data type mismatches.
  • ·         The strict declaration forces things to be used in an intended way.

Ex.

<?Php
function addnumbers(int $a, int $b) {
  return $a + $b;
}
echo addnumbers(5"5 days");
// since strict is not enabled "5 days" is changed to int(5), and it will return 10
?>

Output :- 10

 

To specify strict to set declare (strict_types=1) on the very first line of the PHP file.

 Ex:

<?Php declare(strict_types=1); // strict requirement

function addnumbers(int $a, int $b) {
  return $a + $b;
}
echo addnumbers(5"5 days");
// since strict is enabled and "5 days" is not an integer, an error will be thrown
?>

Output:-

Php fatal error: uncaught typeerror: argument 2 passed to addnumbers() must be of the type integer, string is given.

 

Variable functions (dynamic function calls)

·         Function names as strings to variables and it treats as variables exactly as the function name itself. 

·         This means PHP searches for a function and finds a variable whose name is just like the function name. So evaluates it on the variable, and will try to execute it.

·         It can be used for call-backs, function tables, etc.

·         Variable functions won't work with language constructs such as echoprintunset()isset()empty()includerequire, and the like.                                                                                          

·         Utilize wrapper functions to make use of any of these make as variable functions.

 

Ex.

<html>

     <head>

      <title>dynamic function calls</title>

   </head>

     <body>

           <?Php

         function sayhello() {

            echo "hello<br />";

         }

                 $function_holder = "sayhello";

         $function_holder();

      ?>

     

   </body>

</html>

Output : -

Hello

 

Variable functions are used in following manner:-

Example #1 Variable function example

<?Php
function foo() {
    echo "in foo()<br />\n";
}

function bar($arg = '')
{
    echo "in bar(); argument was '$arg'.<br />\n";
}

// this is a wrapper function around echo
function echoit($string)
{
    echo $string;
}

$func = 'foo';
$func();        // this calls foo()

$func = 'bar';
$func('test');  // this calls bar()

$func = 'echoit';
$func('test');  // this calls echoit()
?>

Object methods can also be called with the variable functions syntax.

 

Example #2 Variable method example

<?Php
class foo
{
    function variable()
    {
        $name = 'bar';
        $this->$name(); // this calls the bar() method
    }
    
    function bar()
    {
        echo "this is bar";
    }
}

$foo = new foo();
$funcname = "variable";
$foo->$funcname();  // this calls $foo->variable()

?>

When calling static methods, the function call is stronger than the static property operator:

 

Example #3 Variable method example with static properties

<?Php
class foo
{
    static $variable = 'static property';
    static function variable()
    {
        echo 'method variable called';
    }
}

echo foo::$variable; // this prints 'static property'. It does need a $variable in this scope.
$variable = "variable";
foo::$variable();  // this calls $foo->variable() reading $variable in this scope.

?>

 

Example #4 complex callable

<?Php
class foo
{
    static function bar()
    {
        echo "bar\n";
    }
    function baz()
    {
        echo "baz\n";
    }
}

$func = array("foo", "bar");
$func(); // prints "bar"
$func = array(new foo, "baz");
$func(); // prints "baz"
$func = "foo::bar";
$func(); // prints "bar"
?>

 Setting default values for function parameter (default argument)

·         Php allows us to set default argument values for function parameters.

·         If we do not pass any argument for a parameter with a default value then PHP will use the default set value for this parameter in the function call.

Syntax:

Function function_name($first_parameter, $second_parameter=value) {

    executable code;

}

 Example:

 <?Php

  // function with default parameter

Function def ($str, $num=18) 

{

    echo "$str is $num years old \n";

}

  // caling the function

Def ("ram", 20);

  // in this call, the default value 18 

// will be considered

Def ("adam");

  ?>

 Returning values from functions (Return from Function)

  • ·         Return values to the part of the program from where it is called.
  • ·         The return keyword is used to return value back to the part of the program, from where it was called.
  • ·         The returning value may be of any type including the arrays and objects.
  • ·         The return statement also marks the end of the function and stops the execution after that and returns the value.

 Example:

<?Php

  // function along with three parameters

Function mul($num1, $num2, $num3) 

{

    $product = $num1 * $num2 * $num3;

      return $product; //returning the product

 }

  // storing the returned value

$retvalue = mul(2, 3, 5);

Echo "the product is $retvalue";

 ?>

 Parameter passing to functions

Two ways

Pass by value: 

  • ·         Passing arguments by value.
  • ·         The value of the argument gets changed within a function, not in the original value outside the function.
  • ·         A duplicate of the original value is passed as an argument.

 

·         Pass by reference: 

  • ·         On passing arguments by reference (address of the value) where it is stored using ampersand sign(&).
  • ·         The original value gets altered.

 

<?Php

  // pass by value  

Function val ($num) {

    $num += 2;

    return $num;

}

 

// pass by reference

Function ref (&$num) {

    $num += 10;

    return $num;

}

  $n = 10;

  Val ($n);

Echo "the original value is still $n \n";

  Ref ($n);

Echo "the original value changes to $n";

  ?>

Output:

The original value is still 10

The original value changes to 20

 

Php variable length argument function

Php supports variable-length argument function. It means you can pass 0, 1 or n number of arguments in the function. We can use  3 ellipses (“…”(triple dots)) before the argument name.

·         Variable: it is the number of arguments that keeps changing.

·         Length: it refers to the number of arguments.

·         Argument: it refers to input passed to a function.

All the arguments passed at its call will go the function as an array. The values will be retrieved like they are being from an array.

The 3 dot concept is implemented for variable length argument since php 5.6.

Example:-

<?Php  

Function add(...$numbers) {  

 $sum = 0;  

Foreach ($numbers as $n) {  

$sum += $n;  

}  

 return $sum;  

}  

  Echo add(1, 2, 3, 4);  

?>  

 Output:

10

 

Providing variable arguments method: you can also use “…”(triple dots) when calling functions to unpack an array or traversable variable or literal into the argument list.

<?Php

Function add($a,$b) {

  return $a + $b ;

}

Echo add(...[1, 2])."\n";

  

$a = [1, 2];

Echo add(...$a);

?>

Output:

3

3

 

Type hinted variable arguments method: it is also possible to add a type of hint before the … token. If this is present, then all arguments captured by … must be objects of the hinted class.

 

<?Php

Function total_intervals($unit, dateinterval ...$intervals) {

    $time = 0;

    foreach ($intervals as $interval) {

        $time += $interval->$unit;

    }

    return $time;

}

  

$a = new dateinterval('p1d');

$b = new dateinterval('p2d');

Echo total_intervals('d', $a, $b).' days';

Echo total_intervals('d', null);

   ?>

Output:

 3 days

Catchable fatal error: argument 2 passed to total_intervals() must be an instance of dateinterval, null given, called in - on line

 

The & reference operator can be added before the ..., but after the type name (if any).

Class foo{}

Function a(foo &...$foos){

    $i = 0;

    foreach($a as &$foo){ // note the &

        $foo = $i++;

    }

}

$a = new foo;

$c = new foo;

$b =& $c;

A($a, $b);

Var_dump($a, $b, $c);

Output:

Int(0)

Int(1)

Int(1)

 

The variable scope

The location of the declaration determines the extent of a variable's visibility within the PHP program.

Where the variable can be used or accessed.

Known as variable scope.

By default, variables declared within a function are local and they cannot be viewed or manipulated from outside of that function, .

 

<?Php // defining function

Function test()

{

$greet = "hello world!"; echo $greet;

}

Test(); // outputs: hello world!

Echo $greet; // generate undefined variable error

?>

Output:-

$greet inside function is: hello world!

$greet outside of function is:

Ex.

<?Php

$greet = "hello world!";

 // defining function

Function test(){

    echo '<p>$greet inside function is: ' . $greet . '</P>';

}

 // generate undefined variable error

Test(); 

 Echo '<p>$greet outside of function is: ' . $greet . '</P>';

?>

Output:-

$greet inside function is:

$greet outside of function is: hello world!

 

The global keyword

It is visible or accessible both inside and outside the function.

Use the global keyword before the variables inside a function.

<?Php

$greet = "hello world!"; // defining function

Function test()

{

Global $greet;

Echo $greet;

}

Test(); // outpus: hello world!

Echo $greet; // outpus: hello world! // assign a new value to variable $greet = "goodbye";

Test(); // outputs: goodbye

Echo $greet; // outputs: goodbye

?>

Output:-

$greet inside function is: hello world!

$greet outside of function is: hello world!

$greet inside function is: goodbye

$greet outside of function is: goodbye

 

Recursive functions

A recursive function is a function that calls itself again and again until a condition is satisfied.

Used to solve complex mathematical calculations, or to process deeply nested structures e.g., printing all the elements of a deeply nested array.

 

<?Php

// defining recursive function

Function printvalues($arr) {

    global $count;

    global $items;

   

    // check input is an array

    if(!is_array($arr)){

        die("error: input is not an array");

    }

   

    /*

    loop through the array, if the value is itself an array recursively call the function,

    else add the value found to the output items array,

    and increment counter by 1 for each value found

    */

    foreach($arr as $a){

        if(is_array($a)){

            printvalues($a);

        } else{

            $items[] = $a;

            $count++;

        }

    }

   

    // return total count and values found in array

    return array('total' => $count, 'values' => $items);

}

 

// define nested array

$species = array(

    "birds" => array(

        "eagle",

        "parrot",

        "swan"

    ),

    "mammals" => array(

        "human",

        "cat" => array(

            "lion",

            "tiger",

            "jaguar"

        ),

        "elephant",

        "monkey"

    ),

    "reptiles" => array(

        "snake" => array(

            "cobra" => array(

                "king cobra",

                "egyptian cobra"

            ),

            "viper",

            "anaconda"

        ),

        "crocodile",

        "dinosaur" => array(

            "t-rex",

            "alamosaurus"

        )

    )

);

 

// count and print values in nested array

$result = printvalues($species);

Echo $result['total'] . ' Value(s) found: ';

Echo implode(', ', $result['values']);

?>

Output:-

16 value(s) found: eagle, parrot, swan, human, lion, tiger, jaguar, elephant, monkey, king cobra, egyptian cobra, viper, anaconda, crocodile, t-rex, alamosaurus.

 

<?Php
function recursion($a)
{
    if ($a < 20) {
        echo "$a\n";
        recursion($a + 1);
    }
}

Recursion (5);
?>

Output:- 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

 

Php static variables

static variable is a variable that has been allocated statically, and whose lifetime extends across the entire run of the program.

The default local variables do not hold their value within repeated calls of the function.

Non_static.php

<?Php

 

Function nonstatic() {

 

    $value = 0;

    $value += 1;

 

    return $value;

}

 

Nonstatic();

Nonstatic();

Nonstatic();

Nonstatic();

 

Echo nonstatic(), "\n";

 

?>

Output:-

1

The static variables are initiated only once when the function is first called. They retain their value afterward.

Static.php

<?Php

 

Function staticfun() {

 

    static $value = 0;

    $value += 1;

 

    return $value;

}

 

Staticfun();

Staticfun();

Staticfun();

Staticfun();

 

Echo staticfun(), "\n";

?>

 

Output:-

5987

======================================================================== 

Post a Comment

0 Comments