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
}
1

3 Answers 3

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']();
Sign up to request clarification or add additional context in comments.

5 Comments

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?
I've shown how to call a function that's stored in the array.
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.
Ahh, now that you've clarified, I've added a duplicate question link that shows how to do it with eval.
This is exactly what I was wanting. It has done the trick beautifully. Thanks for persisting with me.
0

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.