douyi3767 2018-12-20 19:00 采纳率: 0%
浏览 79

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

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条回答 默认 最新

  • douweihui0178 2018-12-20 19:10
    关注

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

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?