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

Tuesday, January 23, 2024

Call by value in Function

Call by value

In PHP, when you pass a variable to a function, the default behavior is "call by value." This means that the value of the variable is passed to the function, and any changes made to the parameter within the function do not affect the original variable outside the function.

Example:

<?php

// Function that takes a parameter and increments it

function incrementValue($num) {

    $num++; // Increment the parameter

    return $num; // Return the updated value

}

// Main program

$originalValue = 10;

// Call the function and store the result in a new variable

$newValue = incrementValue($originalValue);

// Output the values

echo "Original Value: " . $originalValue . "<br>"; // Original Value: 10

echo "New Value: " . $newValue; // New Value: 11

?>

Output:

Original Value: 10

New Value: 11

Explanation:

  1. $originalValue = 10;: This line initializes a variable $originalValue with the value 10.
  2. $newValue = incrementValue($originalValue);: This line calls the incrementValue function with the argument $originalValue. The function increments the value by one, and the result is stored in a new variable $newValue.
  3. echo "Original Value: " . $originalValue . "<br>";: This line outputs the original value of $originalValue, which is still 10.
  4. echo "New Value: " . $newValue;: This line outputs the new value, which is the result of incrementing the original value by one. The new value is 11.


No comments:

Post a Comment

Pages

SoraTemplates

Best Free and Premium Blogger Templates Provider.

Buy This Template