PHP: pass a variable to a function, do something to the variable, return it back

前端 未结 5 1913
孤街浪徒
孤街浪徒 2021-01-22 11:39

Assuming the following code:



        
相关标签:
5条回答
  • 2021-01-22 12:16

    You either have to assign the return value of the doStuff calls back to the local $rowCount variable:

    $rowCount = 1;
    echo $rowCount.' and ';
    $rowCount = doStuff($rowCount);
    $rowCount = doStuff($rowCount);
    $rowCount = doStuff($rowCount);
    

    Or you pass the variable as a reference by putting a & in front of the formal parameter $rowCount:

    function doStuff(&$rowCount) {
        $rowCount++;
        echo $rowCount.' and ';
        return $rowCount;
    }
    

    Now the formal parameter $rowCount inside the function doStuff refers to the same value as the variable that is passed to doStuff in the function call.

    0 讨论(0)
  • 2021-01-22 12:16

    change function doStuff($rowCount)

    to function doStuff(&$rowCount)

    Normally in PHP you're sending a copy of the variable to the function, so modifications within the function will not affect the value of the variable outside of the function. Adding the ampersand tells PHP to send a reference to the variable instead so modifications to the variable propagate back to the caller.

    0 讨论(0)
  • 2021-01-22 12:18

    You need to pass the variable 'by reference' instead of 'by value' to accomplish this add an & to the variable in the function declaration:

    function doStuff(&$rowCount);
    

    Also check out PHP: Passing by Reference

    0 讨论(0)
  • 2021-01-22 12:24

    i would just try to fix the code: ...

    <?php
    function doStuff($rowCount) {
        $rowCount++;
        echo $rowCount.' and ';
        return $rowCount;
    }
    $rowCount = 1;
    echo $rowCount.' and ';
    doStuff(doStuff(doStuff($rowCount)));
    
    ?>
    
    0 讨论(0)
  • 2021-01-22 12:25

    You should try this :

    $rowCount = 1;
    echo $rowCount.' and ';
    $rowCount = doStuff($rowCount);
    $rowCount = doStuff($rowCount);
    $rowCount = doStuff($rowCount);
    

    Your doStuff() method returns an int that is never used when you simply use the statement doStuff($rowCount); without assignation.

    0 讨论(0)
提交回复
热议问题