0

Is there away to pass a variable (with array data) into a function without having to use as a parameter each time I want to use the function?

My situation is that I have producing UI elements for a form. Right now if I define the input's name I get the field which works as designed, but I also have to pass two variables every time.

Function Defined:

function getDecision($name,$game,$answer) { 
  // lots of code not very relevant 
}

Ideally I want to pass the $game and $answer variables inside the function for what is dependent on them. I am using code igniter and the $game variable is passed to the view on load of the page. The $answer variable can be defined within function only if the $game has been passed or define.

Current use of the function:

getDecision('company_name', $game, $answer);

Ideal use of function (simpler use):

getDecision('company_name');

Let me know if there is anything else I need to define, I don't want to show all of the code because there is nearly 100 lines of code.

Anthony
  • 36,459
  • 25
  • 97
  • 163
dvoutt
  • 930
  • 2
  • 9
  • 23

2 Answers2

0

Using closures for this would be a good option - http://php.net/manual/en/functions.anonymous.php, specifically the 'use' construct

#!/usr/bin/env php 
<?php

function getDecision($name, $game, $answer) {
  echo "$name : $game : $answer \n";
}

function main() {

  $my_game = "my game";
  $my_answer = "my answer";


  $getDecisionCaller = function($name) use ($my_game, $my_answer) {
    getDecision($name, $my_game, $my_answer);
  };  

  // Don't really need the line below, can simply use: $getDecisionCaller('company 0');
  getDecision('company 0', $my_game, $my_answer);

  $getDecisionCaller('company 1');
  $getDecisionCaller('company 2');
}

main();

?>

Will give the output

company 0 : my game : my answer 
company 1 : my game : my answer 
company 2 : my game : my answer

In the code above i define getDecision($name, $game, $answer) that simply prints out the values sent. Then, i define getDecisionCaller that accepts only $name an an argument but uses the values of $my_game, $my_answer already defined.

Note - The 'use' construct needs variables to bind to, and you cannot set the values via a string. It will give the error - 'Parse error: parse error, expecting '&'' or"variable (T_VARIABLE)"''

eg. You cannot do the below

$getDecisionCaller = function($name) use ('a game', 'an answer') {
  getDecision($name, $my_game, $my_answer);
};

Hopefully, that helped :)

user3663132
  • 53
  • 1
  • 5
0

You could use global variables to do so. For example:

<?php

    $array = array();

    function test() {
        global $array;

        print_r($array);
    }

    function main() {
        test();
    }

    main();
?>

http://php.net/manual/en/language.variables.scope.php

Although, it should be avoided.

HelpNeeder
  • 6,383
  • 24
  • 91
  • 155