简体   繁体   English

定义php函数时使用变量列表作为参数

[英]Use list of variables as arguments when defining php function

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.回调很简单,我可以使用 (...$listOfVariables) 将所有需要的参数放入回调中,但在定义函数时它不起作用。

I need this because I have 50 different functions that require the use all of the same arguments.我需要这个是因为我有 50 个不同的函数需要使用所有相同的参数。 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 1.在函数外定义的变量

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

2.a variable that contains all of those variables 2.一个包含所有这些变量的变量

$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. 3.include 我可以在函数中使用的变量列表,这样我就不必像在第一个片段中那样一次列出一个。

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? **我意识到 $listOfVar 语法中的逗号对此不正确,但是语法是什么? 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.请帮忙。

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() .如果您事先不知道最终开发人员将在您的函数上使用多少个变量,您可以使用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.我使用这个函数是因为你提到了一个事实,即你不知道最终开发者要放多少参数。

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'];
}

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或者你可以使用 list() 方法

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

name(array(‘var1text’, ‘var2text’));

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?也许这可能是更改变量列表的中心位置?

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM