Chuxin
Chuxin

Reputation: 89

PHP function - compare with the following examples

  1. compare with the two similar examples and please tell me why?
  2. please explain it clearly.

    function inc(&$value, $amount = 1) {
        $value = $value + $amount;
        echo $value;    //21
    }
    
    $val = 20;
    inc($val); 
    echo "<br>$val";   //21
    
    echo "<hr>";
    
    function incSec(&$value, $amount = 1) {
        $value = $value + $amount;
        echo $value;    //21
    }
    
    incSec($valSec = 20);   
    echo "<br>$valSec";    //20
    

I'm trying to test, but can't get the reason.

Upvotes: 1

Views: 90

Answers (2)

Aleks G
Aleks G

Reputation: 57336

First, the second example you posted will output the other way around: "21" inside the function and "20" in the main body - test it yourself.

Now, for the exlanation... To start with, the increment amount will always be 1, because you're not passing an explicity amount into the function.

In the first example, you assign a value to the variable, then pass that variable into a function by reference and in the function you increment the value. The function will receive parameter "20", inrement it by a (default) amount of 1 and prints the result - "21". After the function returns, the value (as it was passed by reference) is now incremented - and another "21" is printed.

In the second example, you assign 20 to your variable and pass into the function the result of that assignment. The result will be 20, but it will be a different location in memory. From the point of view of the function, it just receives a by-ref parameter with value 20, increments it and prints the result - hence you get "21". When the function returns, you then print the value of your variable - which never was passed into the function (and therefore never incremented) - hence you get "20" printed.

Upvotes: 6

Mark Baker
Mark Baker

Reputation: 212492

Suspect you're getting an error with these lines:

incSec($valSec = 20); 

This isn't passing $valSec to the function, it's passing the result of the assignment of 20 to $valSec (typically a succesful assignment). The value of that result is 20 (assuming success), but it isn't a variable, it's merely a result.

Your incSec function() is defined to expect a variable passed by reference, but you can only reference a variable, not a result.

Upvotes: 0

Related Questions