What is PHP Function? Explained for Beginners

PHP
PHP Function Tutorial

A PHP Function is a block of code that will execute when the function is called. Functions are very useful to increase code reusability and make your code easy to understand, easy to maintain, and easy to debug.

<?php
// A Simple Function
function sayHello(){
  //Code To Be Executed;
  echo "Hello";
}

// Function Calling
sayHello();

Types of PHP Function

There are two major types of Functions in PHP –

1) πŸ“₯ Built-in Functions

  • The Built-in Functions are already coded by PHP creators and stored as functions.
  • PHP provides us with a very large collection of built-in functions and these functions are very helpful for developing PHP applications.

2) πŸ‘· User-Defined Functions

Apart from the built-in functions, PHP also allows us to create our own custom functions and when we create our own custom functions it is called user-defined functions.


How to create and call a PHP Function?

Follow the below steps to create and call a Function –

1) Function Keyword

Whenever you create a function you must first type the function keyword.

<?php

function

?>

2) Name of the Function

After typing the function keyword, you need to give one space, and then give a unique name with parentheses for identifying the function.

<?php

function my_function_name()

?>

3) Code that will be executed

After the function is named, now add curly braces, and write the code inside the curly braces that will be executed.

<?php

function my_function_name()
{
   echo "Hello World";
}

?>

4) Call the Function

To call a function you need to write the function name with parentheses, and you can call a function multiple times.

<?php

my_function_name();

?>

πŸ‘‰ Example

<?php

function sayHello()
{
   echo "Hello World";
}

// Calling the sayHello function
sayHello();

?>
Browser Output
Hello World

Function Naming Convention

The function name must follow the below naming conventions –

  • Function Name must start with a letter or underscore ( _ ).
  • Do not use reserved keywords or predefined constants.
  • Function names are case-insensitive. syhello() and sayHello() Both are the same.

PHP Function Parameters or Arguments

The parameters or arguments of a function are used to make a function dynamic.

Parameters are the variables that are declared inside the parentheses of the function. And the function parameters are only accessible inside the function.

PHP function parameter

Pass Multiple Parameters

Using comma (,) you can pass multiple parameters inside a function. The comma is used to separate multiple parameters.

function with multiple parameters

Pass values ​​into the function parameters

At the function calling time, you can pass values to the parameters. And the order of the parameters and values ​​should be the same.

Pass values ​​into the function parameters

Example of a dynamic Function

<?php
  function showUser($name, $email, $age){
    echo "<table>
    <tr>
    <td><strong>Name:</strong></td>
    <td>$name</td>
    </tr>
    <tr>
    <td><strong>Email:</strong></td>
    <td>$email</td>
    </tr>
    <tr>
    <td><strong>Age:</strong></td>
    <td>$age</td>
    </tr>
    </table>";
  }

  showUser("John", "[email protected]", 21);
  echo "<br>";

  showUser("Mark", "[email protected]", 25);
  echo "<br>";

  showUser("Barry", "[email protected]", 19);
?>
Browser Output
Name:John
Email:[email protected]
Age:21

Name:Mark
Email:[email protected]
Age:25

Name:Barry
Email:[email protected]com
Age:19

Function Return Statement

The Function Return statement is used to return any type of data, such as string, number, array, boolean, etc.

<?php
  function myFunc(){
      $var = 'Hello John';
      //The return keyword is used to return data
      return $var;
  }

  // Assigning return data into the variable
  $returnData = myFunc();
  echo $returnData;

  /* OR you can also do this
  echo myFunc();
  */
?>
Browser Output
Hello John

You can return only one data at a time. But, you can return multiple data using the PHP array.

<?php
  function myFunc(){
      $var = 'Hello John';
      $var2 = "Hello Jean";

      /* Invalid
      return ($var, $var2);
      */

      // Right way
      $data = array($var, $var2);
      return $data;
  }

  $returnData = myFunc();
  echo $returnData[0]."<br>";
  echo $returnData[1];
?>
Browser Output
Hello John
Hello Jean

Difference between Echo and Return

The echo statement is used to output one or more strings. But, the Return statement is used to return any type of data.


PHP Function Type Declaration

When you pass an argument inside a function, you can declare the data-type of the argument and that is called function type declaration.

After declaring the data-type, you have to pass the same specified type of value as the argument. Otherwise, you will get a type-error.

How to declare type?

<?php
  function myFunc(type $arg1, type $arg2){
    //Code To Be Executed;
  }
?>

In the following example, the integer (int) type declared in both arguments. Therefore, you have to pass the integers as the value of the function arguments.

<?php
  function myFunc(int $num1, int $num2){
      return $num1 + $num2;
  }

  $returnData = myFunc(21,30);
  echo $returnData;

  /*You can't do this
  $returnData = myFunc("Hello",30);
  */
?>
Browser Output
51

Not only in the function arguments, but you can also specify the return data-type, which means what type of data the function will return.

<?php
  function myFunc(type $arg) : return_type {
    //Code To Be Executed;
  }
?>
<?php
  function myFunc(string $name) : string {
      return $name;
  }

  $returnData = myFunc("John Doe");

  echo $returnData;
?>
Browser Output
John Doe

Type Declaration in coercive and strict mode

✍ Coercive mode

The coercive mode is the default behavior of the PHP type Declaration. This mode helps to convert (If the conversion is possible) the type of the argument value ​​according to the specified type.

In the following example, the Coercive mode converted the integer to a string. 25 to "25".

<?php
  function myFunc(string $val){
      return $val;
  }

  $returnData = myFunc(25);

  echo "$returnData <br>";

  // The PHP gettype() function is used to Get the type of a variable
  echo "$returnData is a ".gettype($returnData);
?>
Browser Output
25
25 is a string

✍ Strict mode

The strict mode is the opposite of the coercive mode. In this mode, you must pass or return the same type of value that is declared. Otherwise, you will get the type-error.

To use the strict mode, first, you have to enable it –

<?php 
  declare(strict_types=1);
?>
<?php
  declare(strict_types=1);

  function myFunc(string $val){
      return $val;
  }

  /* You Can't do this
  $returnData = myFunc(25);
  */

  $returnData = myFunc("25");

  echo "$returnData <br>";
  echo "$returnData is an ".gettype($returnData);
?>
Browser Output
25
25 is an integer

PHP Scalar and Return type declaration

When you declare a type on an argument, it is called a scalar type declaration. But, when you declare a type on the return statement, then it is called a return type declaration.


PHP function Pass By Value and Pass By Reference

Pass by value

Pass by value is when you pass a variable as the function argument and modify this argument it does not affect the original variable, and this is the default behavior.

<?php
  $num = 12;
  function myFunc($arg){

      // changing the argument value
      $arg = 7;
      echo "Inside Function - $arg";

  }

  myFunc($num);

  echo "<br>";
  echo "Original Variable - $num";
?>
Browser Output
Inside Function – 7
Original Variable – 12

Pass by Reference

Pass by reference is the inverse of the pass by value, that means when you modify the function argument it will affect the original variable.

The β€œ&” Is used to activate pass by reference for the variable.

<?php
  $num = 12;
  function myFunc(&$arg){

      // changing the argument value
      $arg = 7;
      echo "Inside Function - $arg";

  }

  myFunc($num);

  echo "<br>";
  echo "Original Variable - $num";
?>
Browser Output
Inside Function – 7
Original Variable – 7

Recursive Function

When a function calls itself, it is called a recursive function. But, be careful when you create a recursive function as it can break your server or application.

<?php
  function myFunc(){ 
      myFunc();
  }
  myFunc();
?>

The following example displays numbers from 1 to 10. Read the following code and try to understand.

<?php
  function showNum($start,$end){
      //checking $start is less than or equal to $end
      if($start <= $end){
          // if $start is not equal to $end
          if($start !== $end){
              echo "$start<br>";
              showNum(++$start,$end);
          }
          else{
              echo $start;
          }

      }
      else{
          echo "Your Starting number is grater than ending number";
      }
  }

  showNum(1,10);
?>
Browser Output
1
2
3
4
5
6
7
8
9
10

Anonymous Function in PHP

Those functions are Anonymous functions which have no specified name. The Anonymous functions are also known as β€œclosuresβ€œ & they are most useful as the value of callback parameters.

Anonymous functions are works like a normal function but behave like a value/expression. Therefore you have to add a semicolon after ending the function or sometimes you have to add a comma or nothing.

<?php
  $var = function(){
    //Code To Be Executed;
  };

  //  Calling the Anonymous Function
  $var();
?>

Passing Arguments

You can pass arguments into the anonymous function the same as the normal function.

Inheriting variables

But, if you want to Inherit a variable from the parent scope, then you have to use the "use()" language construct.

<?php
  $name = "John Doe";

  $myFunc = function() use($name){
    echo "Hello, $name";
  };

  $myFunc();
?>
Browser Output
Hello, John Doe

πŸ‘‰ Pass an Anonymous Function as a function argument –

<?php
  function myFunc($theFunc){
    /*
      Inside of the $theFunc

      $theFunc = function(){
        return "Hello, From Callback";
      };
    */
  
   // calling the Arg Function
    echo $theFunc();
  }

  myFunc(function(){
    return "Hello, From Callback";
  });
?>
Browser Output
Hello, From Callback

πŸ‘‰ You can also return an anonymous function from a function –

<?php
  function myFunc(){
    return function(){
      return "Hello from return!";
    };
  }

  /* 
  Inside of the $sayHello -

  $sayHello = function(){
    return "Hello";
  };
  */

  $sayHello = myFunc();
  echo $sayHello();
?>
Browser Output
Hello from return!

Anonymous function in an array

You can alos add anonymous function to an array value.

<?php
    $myArray = [
        'SayName' => function($name){
            return $name;
        },
        'age' => 21
    ];

    $sayName = $myArray['SayName'];
    echo $sayName("John Doe");
?>
Browser Output
John Doe

PHP IFI Function

If you want to call an anonymous function without assign to a variable or passing to arguments, you can do that by the helping of IFI (Immediate function invocation).

<?php
    (function(){
        echo "Hello IFI";
    })();
?>
Browser Output
Hello IFI
Tags

You May Also Like

Leave a Comment

Your email address will not be published. Required fields are marked *