0

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.

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
}
Mark
  • 195
  • 1
  • 18
  • possible duplicate of [PHP: define functions with variable names](http://stackoverflow.com/questions/7337883/php-define-functions-with-variable-names) – Barmar Mar 03 '14 at 16:44

3 Answers3

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']();
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Thanks for your answer. This does not seem to iterate through the loop setting up functions with the names of the elements of the array. When I call functions with names from the array, I get the error message call_user_func_array() expects parameter 1 to be a valid callback, function 'enrolment' not found or invalid function name. Is there any special way to call these functions? – Mark Mar 02 '14 at 13:19
  • I've shown how to call a function that's stored in the array. – Barmar Mar 03 '14 at 05:44
  • I don't think I asked the question clearly enough. I want to be able to declare the functions with names taken from an array, not place the functions into an array to be called by accessing elements of the array as you have shown above. I think though that it may be possible for me to use your solution anyway but I'll need to ask another question about referencing functions in the Wordpress add_submenu function. – Mark Mar 03 '14 at 08:19
  • Ahh, now that you've clarified, I've added a duplicate question link that shows how to do it with `eval`. – Barmar Mar 03 '14 at 16:45
  • This is exactly what I was wanting. It has done the trick beautifully. Thanks for persisting with me. – Mark Mar 12 '14 at 14:22
0

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

Ed Heal
  • 59,252
  • 17
  • 87
  • 127
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.

Community
  • 1
  • 1
drewish
  • 9,042
  • 9
  • 38
  • 51