Dave Anthony Gordon
Dave Anthony Gordon

Reputation: 25

Passing variables from one function to another

I have set a variable in one function and I am trying to use it in another. People seem to be advising against using globals for functions.

This code is in my first variable

 if($this->CheckAndSetupContractHitman($player_data_tab,$player_defence_data_tab)) $winner_exp = $winner_exp + floor($winner_exp*0.4);

 if($this->CheckAndSetupContractHitman($player_data_tab,$player_defence_data_tab)) $bonus_exp = floor($winner_exp*0.2857); 

It is the variable $bonus_exp that I am trying to pass on to another function. Should I add return $bonus_exp; at the end of the first variable and then add $bonus_exp as an argument to the second variable like so?

function CheckAndSetupContractHitman($player_data_tab,$player_defence_data_tab,$bonus_exp)

Upvotes: 0

Views: 75

Answers (3)

Ahmet Uğur
Ahmet Uğur

Reputation: 472

Basicly there are 2 ways to get some variables from a function.

Firstly as you said pass by reference.

Other one is a return value. It is possible to get more than 1 value with return, when you return an array like:

if(expression){
    return ["exp" => $exp, "bonus",$bonus];
} else {
   return false;
}    

So you can use like

if($array = topFunction($param1,$param2)){
    $exp = $array["exp"];
    $bonus = $array["bonus"];
}

I prefer second one. You should not execute 2 times same function.

Upvotes: 0

Zak
Zak

Reputation: 7523

I would do as you suggest, using a return and passing the parameter. With one exception: Make it equal nothing (empty) -- That way .. The function doesn't technically need it as an input, and you can simply include it, or not, at your discretion.

function CheckAndSetupContractHitman($player_data_tab,$player_defence_data_tab,$bonus_exp = ''){
    if ($bonus_exp != ''){
        // Do something
    }
// ....
return bonus_exp;
}

Set up this way -- If you call the function without $bonus_exp IE

CheckAndSetupContractHitman($player_data_tab,$player_defence_data_tab);

$bonus_exp will be set to ''

But if you have it set and pass it in ... It will be set to whatever you passed. IE

$bonus_exp = 50;
CheckAndSetupContractHitman($player_data_tab,$player_defence_data_tab,$bonus_exp);

$bonus_exp would be passed as 50 into the function.

Upvotes: 0

Reyo Stallenberg
Reyo Stallenberg

Reputation: 21

Maybe you are looking for Passing by Reference

I think you should think out another solution for your problem, but Passing by Reference is better then using globals.

Upvotes: 1

Related Questions