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

报告相同问题?

悬赏问题

  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 正弦信号发生器串并联电路电阻无法保持同步怎么办
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)