Use list of variables as arguments when defining php function

668 Views Asked by At

I am trying to use a list of variables as arguments when DEFINING a function. It seems like it should be straight forward, but no. The callback is easy and I am able to use (...$listOfVariables) to get all needed arguments into callback, but it does not work when defining the function.

I need this because I have 50 different functions that require the use all of the same arguments. When the list of arguments changes (which it does) I need a central location to make sure all of the different functions use the new list of arguments. (Again, I already can do this with the callback, but not when I define the function)

Here is how I would normally do it for a few arguments.

$var1 = 'var1text';
$var2 = 'var2text';
$var3 = 'var3text';


function funcname($var1, $var2, $var3){

    echo $var1;
}

That works fine, but my list of variables changes a lot and is used in many other functions. I may be going about it the wrong way and I'm open to whatever suggestions you have. Below is what I need to accomplish.

EDITED

1.variables that are defined outside of the function

$var1 = 'var1text';
$var2 = 'var2text';
$var3 = 'var3text';

2.a variable that contains all of those variables

$listOfVar = $var1, $var2, $var3; //***see note below***.

3.include list of variables that I can use within the function so I don't have to list them one at a time like I did in the first snippet.

function funcname($listOfVar){

    echo $var1;
}

the full code I am trying to make work:

$var1 = 'var1text';
$var2 = 'var2text';
$var3 = 'var3text';

$listOfVar = $var1, $var2, $var3;

function funcname($listOfVar){

    echo $var1;
}

**I realize the commas in the $listOfVar syntax is not correct for this, but what IS the syntax then? I've tried variable variables ($$) - trying to convert a string to variable name references. I have tried arrays. I have tried literally hundreds of variations of these and I am just out of ideas for this. Please help.

5

There are 5 best solutions below

0
Nigel Ren On

If instead you use an array for the passed data...

function funcname($vars){
    echo $vars[0];
}

Although it has advantages not sure if this would be a good idea, but you could also use an associative array...

function funcname($vars){
    echo $vars['var1'];
}
1
Dave On

Simply put your variables in an array and pass the name of the array to your function.

$vararray[] = 'var1text';
$vararray[] = 'var2text';
$vararray[] = 'var3text';
funcname($vararray);

function funcname($variable_array){
    echo $variable_array[1];  // will echo var2text
}
2
Anwar On

If you do not know in advance how many variables does the end developper will use on your function, you can use func_get_args(). It returns every variables values as an array.

Here is an example of usage:

function foo() {
  $arguments = func_get_args();

  return $arguments;
}

print_r(foo(1, 2, 3)); // [1, 2, 3]
print_r(foo('a', 'b', 'c')); // ['a', 'b', 'c']

I used this function because you mentioned the fact that you do not know in advance how many parameters the end developper is going to put.

22
Jaquarh On

In future, read How to create a Minimal, Complete, and Verifiable example so we can understand your question in order to help you.

Methods have there own scope, meaning unless otherwise declared or passed through, the method will not have access to the variable.

class Retriever {
    private static $instance;
    protected $listOfVars = array();

    public static function getInstance() {
        if(self::$instance) return self::$instance;
        self::$instance = new self();
        return self::$instance;
    }

    private function __construct() {}

    public function addVar($var) { array_push($this->listOfVars, $var); return $this; }
    public function getVars() { return $this->listOfVars; }
    public function reset() { $this->listOfVars = array(); return $this; }
}

function name($var1, $var2, $var3) {
    echo $var1;
}
function anotherName($var1, $var2) {
    echo $var2;
}

Retriever::getInstance()->addVar("var1text")->addVar("var2text")->addVar("var3text");
name(...Retriever::getInstance()->getVars()); # Output: var1test

Retriever::getInstance()->reset()->addVar("var1text")->addVar("var2text");
anotherName(...Retriever::getInstance()->getVars()); # Output: var2text

Live demo.

Or you can use the list() method

function name($listOfVars) { 
    list($var1, $var2) = $listOfVars;
    echo $var1;
}

name(array(‘var1text’, ‘var2text’));
9
Don't Panic On

Maybe you could modify your function so that it takes an array instead of multiple arguments.

function funcname(array $args){
    foreach ($args as $arg_name => $arg) {
        // do stuff with $arg_name and $arg
    }
    // or refer to a specific argument, like where you would have said $var1, instead...
    $args['var1'];
    // or extract the array within your function to get the keys as variables
    extract($args);
    echo $var1;
    // If you do this, be sure to heed the warnings about extract.
    // Particularly the bit about not extracting $_GET, $_POST, etc.
}

Then instead of defining separate variables like

$var1 = 'var1text';
$var2 = 'var2text';
$var3 = 'var3text';

Create an associative array

$text['var1'] = 'var1text';
$text['var2'] = 'var2text';
$text['var3'] = 'var3text';

If you have multiple functions that need to use the same varying list of arguments, I think it makes sense to collect them in a class. Then you can pass the associative array of arguments to the class constructor so all the methods will have access to the same set of variables.

class SomeFunctions
{

    private $listOfVar = [];

    public function __construct(array $listOfVar) {
        $this->listOfVar = $listOfVar;
    }

    public function funcnameA() {
        foreach ($this->listOfVar as $name => $value) // ...
    }

    public function funcnameB() {
        $this->listOfVar['var1'];
    }
}

$example = new SomeFunctions(['var1' => 'something', 'var2' => 'something']);
$example->funcnameA();
$example->funcnameB();

If you need to use these functions as callbacks, you can pass them like this as the callback parameter:

functionThatTakesaCallback([$example, 'funcnameB']);

Maybe this could be the central location to change the variable list?