skip to Main Content

I have a question about how to pass the data of a variable from one function (a) to another function (b). For example, in the following case…

function a(){
$a = 8;
}

function b(){
$copy_var = $a
}

I intend that in function b, $copy_var is 8, just as in function a $a is equal to 8. I can’t think of how to do it… Thanx!!

2

Answers


  1. You should take a look at variable scope. Both $a and $copy_var are local variables, which means they exist only within the context of function body, nowhere else, so you cannot point or reference to them.

    You could use global variable to which both functions have access, but keep in mind that introduce hidden dependency which is generally bad. Example:

    $a = 1; // this line is not necessary, but for simple example
    
    function a(){
        global $a;
        $a = 8;
    }
    
    function b(){
        global $a;
        $copy_var = $a
    }
    

    Please do not use global variables like this, as you can see now all the sudden the execution order matter due to the hidden dependency.

    Imagine following code:

    a();
    b(); // the $copy_var value is 8
    

    In contrast to:

    b(); // the $copy_var value is 1
    a();
    

    You see why is it bad ? without looking at both function definitions you have no idea that call to one can affect the other. In complex application this design mistake, which using global variables is in 99% of cases, could cost you hours or even days of frustrating debugging of your application.

    Way better is to carry the value through function parameters and return value (maybe even reference but lets keep that away for now), that way you know just by looking at the call code what will happen.

    function a(){
        $a = 8;
        //...
        return $a;
    }
    
    function b($input){
        $copy_var = $input;
        //...
    } 
    

    Now the call code is way cleaner, look:

    $a = a();
    b($a);
    // ^ absolutely clear that you carry value from one function to another
    
    // or one liner
    b(a());
    
    // now it is impossible to make mistake by changing the call order
    b(); // error: too few arguments
    
    Login or Signup to reply.
  2. Don’t use global, use function parameters and/or return values

    function b($param)
    {
        echo 'param is '.$param;
    }
    
    function a()
    {
        $local = 0;
        b($local); // see comment below
        return $local;
    }
    
    a();
    
    // or like this, assumimg that a() doesn't call b() directly
    $return = a();
    b($return);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search