PHP Call By Value

In PHP, function arguments are passed by value by default. This means that a copy of the value of the argument is created and passed to the function, rather than the original variable itself. Any changes made to the argument variable within the function do not affect the original variable outside of the function.

Here’s an example that demonstrates how call by value works in PHP:

function addOne($num) {
    $num += 1;
    echo "Inside function: $num\n";
}

$num = 10;
addOne($num);
echo "Outside function: $num\n";

In this example, the addOne function takes a single argument $num and adds 1 to it. When the function is called with the value 10, a copy of that value is passed to the function. Inside the function, the value of $num is incremented to 11, but this does not affect the original value of $num outside of the function. When the function returns, the value of $num is still 10, and this is what is echoed to the screen.

While call by value is the default behavior in PHP, you can use the & symbol to pass arguments by reference instead. This allows you to modify the original variable outside of the function.

Wordpress Social Share Plugin powered by Ultimatelysocial
Wordpress Social Share Plugin powered by Ultimatelysocial