Store function name in database and then execute i

2020-05-04 00:03发布

问题:

I am making a kind of CMS system that works in sections of the webpage, and stores each one as a different entry into a table on a database with MySQL. When the user first sets up the page, the PHP script calls a function called addsection($name, $content) that adds the section to the database. However, to make this system more flexible, so it doesn't use static sections, I would like to be able to change the function to be addsection($name, function), where you give a function for the parameter function. Is there any way that I could store this function or function name in the database and then call it when the code needs to get the section text? And if not, what would I be able to do instead? The function that I use to get the content of the section is simply section($name).
Also, does anybody know an easy way to redirect to another page if the current page has not been viewed before that doesn't use files or anything?

回答1:

You can use variable functions (http://php.net/manual/en/functions.variable-functions.php).

$r = mysql_query("SELECT method FROM method_table WHERE id = 2");
$row = mysql_fetch_assoc($r);
$func = $row['method'];
$func($parameter); //will execute whatever method you stored in the `method` field

In this way you can execute a function who's name is stored in a database. If you want to execute it within the context of an object (hence the method), you can do: $this->$func($parameter);