PHP Functions


Function is a set of statements that perform a specific task which enclosed by {}. 

 

There are 3 components of function. They are:

  • Function Prototype/Declaration
  • Function Definition
  • Function Call

Syntax:-

return_type function_name (parameter or argument list)
{
	function body;
}

Function Prototype/Declaration:

Function declaration informs the compiler about the name of the function, types of arguments, the number of arguments, and type of return value.


The value has been promoted from int to double and we have not to specify any type-casting operator. This is known as standard conversion.

PHP function declaration

Syntax

return_type function_name([argument type]);

 

It does not require name of arguments to be provided, type of arguments can be specified.


Function Definition:

It consists body of the function. The body consists of a block of statements to be performed. When a function is called, the responsibility is transferred to the function definition.

return_type function_name([arguments])
{
	statement(s);
}

Function Call:

It is made by using a call statement. It consists of the function name and required argument enclosed in round brackets.

PHP calling and called function

Syntax

function_name([actual arguments]);

Advantages Of Function:

  • Avoid repetition of codes.
  • Code re-usability.
  • Increases program readability.
  • Develop an application in modules.
  • Divide a complex problem into simple.
  • Debugging in the program is easy.
  • Modifying the program becomes easy.
  • In function no need to write a lot of code.
  • Reduces chances of error.

Example:-

<?php
// Function declaration and definition
function sum($num1, $num2) {
    $sum = $num1 + $num2;
    return $sum;
}

// Main logic
$a = 100;
$b = 12;
$result = sum($a, $b); // Calling the function

echo "Sum of two numbers value is : " . $result . "\n";
?>

Types Of Functions:

There are two types of functions. They are

  • Library functions
  • User-defined functions

Four different types of function calls.

  • Function with arguments and with return value.
  • Function with arguments and without return value
  • Function without arguments and with return value
  • Function without arguments and without return value



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.