在循环中创建函数,其中包含php中数组中元素的名称

时间:2021-09-25 15:40:00

I am trying to build a website that contains forms that allow users to edit, view and delete records in mySQL tables. I have managed this. Now I want the user to be able to add new forms and tables, but I would need to be able to create functions with names based on elements in an array.

我正在尝试构建一个包含允许用户编辑,查看和删除mySQL表中记录的表单的网站。我已经成功了。现在我希望用户能够添加新的表单和表格,但我需要能够根据数组中的元素创建名称的函数。

The code below doesn't work, but is there anything else that would?

下面的代码不起作用,但还有什么呢?

for ($i=0;$i<count($tables);$i++) {

function $tables[$i][form]() {
}
// do something
}

3 个解决方案

#1


1  

Use anonymous functions:

使用匿名函数:

for ($i = 0; $i < count($tables); $i++) {
    $tables[$i]['form'] = function() {
        ...
    };
}

Then you call one of the functions as:

然后你调用其中一个函数:

$tables[$i]['form']();

#2


0  

Here is an idea. Have one function and pass those items as parameters. Might work!

这是一个想法。有一个函数并将这些项作为参数传递。可能会工作!

#3


0  

You could use anonymous functions or, use create_function (kind of hacky though since you define the function as a string)... but I think Ed Heal's answer probably best. Just have one function and pass the values that differ by table in as parameters... Or have a class that wraps each table and then you could have the function on the class.

你可以使用匿名函数,或者使用create_function(虽然你将函数定义为一个字符串,但是我觉得Ed Heal的答案可能是最好的)。只需要一个函数并将表中不同的值作为参数传递...或者有一个包装每个表的类,然后你就可以在类中使用该函数。

#1


1  

Use anonymous functions:

使用匿名函数:

for ($i = 0; $i < count($tables); $i++) {
    $tables[$i]['form'] = function() {
        ...
    };
}

Then you call one of the functions as:

然后你调用其中一个函数:

$tables[$i]['form']();

#2


0  

Here is an idea. Have one function and pass those items as parameters. Might work!

这是一个想法。有一个函数并将这些项作为参数传递。可能会工作!

#3


0  

You could use anonymous functions or, use create_function (kind of hacky though since you define the function as a string)... but I think Ed Heal's answer probably best. Just have one function and pass the values that differ by table in as parameters... Or have a class that wraps each table and then you could have the function on the class.

你可以使用匿名函数,或者使用create_function(虽然你将函数定义为一个字符串,但是我觉得Ed Heal的答案可能是最好的)。只需要一个函数并将表中不同的值作为参数传递...或者有一个包装每个表的类,然后你就可以在类中使用该函数。