"Welcome to our PHP 101 blog, where we demystify the world of web development. "

Tuesday, January 23, 2024

Call By Reference in Function

Call By Reference in Function

In PHP, when you pass a variable to a function with an ampersand (&) before the parameter name, it is passed by reference. This means that any changes made to the parameter inside the function will directly affect the original variable outside the function. Here's an example to illustrate call by reference in PHP:

Example:

<?php

// Function that takes a parameter by reference and increments it

function incrementValueByReference(&$num) {

    $num++; // Increment the parameter by reference

}

// Main program

$originalValue = 10;

// Call the function with the original variable by reference

incrementValueByReference($originalValue);

// Output the updated value

echo "Updated Value: " . $originalValue; // Updated Value: 11

?>

Output:

Updated Value: 11

Explanation:

  1. This function, incrementValueByReference, takes a parameter $num with an ampersand (&) before it, indicating that it is passed by reference.
  2. Inside the function, the parameter $num is incremented by one.
  3. The main program initializes a variable $originalValue with an initial value of 10.
  4. The function incrementValueByReference is called with the original variable $originalValue as an argument.
  5. Since the parameter is passed by reference, any changes made to $num inside the function will directly affect the original variable.
  6. The script outputs the updated value of $originalValue after the function call.
  7. In this case, the original value (10) is incremented by the function, and the output will be "Updated Value: 11".
  8. So, the key concept here is that using the ampersand (&) before a parameter in a function declaration allows that parameter to be passed by reference, and any modifications to the parameter inside the function directly affect the original variable passed to the function.






No comments:

Post a Comment

Pages

SoraTemplates

Best Free and Premium Blogger Templates Provider.

Buy This Template