Course Content
State Management
0/1
Regular Expressions?
0/1
About Lesson

What is the main purpose of using functions?

The primary purpose of functions is to break up complicated computations into meaningful chunks and name them. The functions may return a computed value to its caller (its return value), or provide various result values or output parameters.

Call a function:

To call the function, juts write its name followed by parentheses( ):

PHP
<?php

function_name( );

?>

Parameters vs Arguments:

Parameters are temporary variable names within functions.

The arguments can be thought of as the vale that is assigned to that temporary variable.

For example:

PHP
<?php

 function welcome_user($username)

{

  echo ‘Welcome’ . $username. ! ;

?>

In this example $username is a function parameter.

<?php

welcome_user(‘Admin’);

?>

In this function call, the literal string ’Admin’ is an argument.

Use return statement to return a value from a function.

Call By Reference:

In case of PHP call by reference, actual value is modified if it is modified inside the function. In such case, you need to use & (ampersand) symbol with formal arguments. The & represents reference of the variable.

PHP
<?php

// Function that modifies the value of a variable passed by reference

function increment(&$num) {

    $num++;

}

// Using call by reference

$value = 10;

echo "Before increment: $value <br>"; // Outputs: Before increment: 10

increment($value);

echo "After increment: $value"; // Outputs: After increment: 11

?>

In the ‘increment( )’ function, ‘$num’ is passed by reference with’&$num’. This means any changes mde to ‘$num’ inside the function will directly affect the original variable passed to it.

Without passing by reference, changes made to variables inside a function are confined to the function’s scope and do not affect the variables outside the function. However with call by reference, changes made insde the function affect the original variables.