Store function name in database and then execute it

寵の児 提交于 2019-12-20 06:39:08

问题


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);



来源:https://stackoverflow.com/questions/14020129/store-function-name-in-database-and-then-execute-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!