What is PHP call by value?
PHP call by value is the term in which we pass the value directly to the function. However, it does not affect the value outside of the function.
A function is the best part of PHP you can use to reduce your coding size. You don’t need to write the same code again and again. Just put it in a function and call that function from anywhere in your coding.
Call by value is the best and the oldest part of PHP function many developers using when they create a simple function.
You can pass as many variables as you want. But developers prefer to use not more than three variables to pass to a function. It’s the best practice when you don’t want to make your coding more complex to understand.
The value of the source variable remains same when you call the function and print the variable using the echo statement. The default function is the call by value function.
Let’s take a look at some examples given below.
Example1: Passing single value
The example showing below contains a function named Add. A call by value is showing here by passing the value directly to the function.
1 2 3 4 5 6 7 8 9 10 11 12 |
<?php function Add($x){ $x = $x+5; return($x); } $n = 10; echo Add($n)."<br>"; echo "The source variable is".$n; } ?> |
Output
The source variable is 10
The function returns the variable and then after we declare a variable $n. You can check here when we print the function by passing the $n variable. it does not change the source value and the source value remains same(e.g. 10).
Example2: Passing two values
The example showing below contains a function named Myval. Two variables are directly passing to the function.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?php function Myval($x,$y){ $x = $x+5; $y = $y-5; echo "The values are ".$x." and ".$y; } $a = 10; $b = 15; Myval($a,$b); echo "<br>"."The source values are ".$a." and ".$b; } ?> |
Output
The source values are 10 and 15
You must read:-
Reference