对于那些想知道我在说什么的人,这里是一个示例 WordPress 插件,它演示了动态函数创建是如何派上用场的。
/* Plugin Name: Sample Action Hooks with Dynamic Functions */
// assuming this is an option retrieved from the database
$oActions = array( 'a' => array('interval' => 10, 'value' => 'hi'),
'b' => array('interval' => 30, 'value' => 'hello'),
'c' => array('interval' => 60, 'value' => 'bye')
);
add_action('init', LoadEvents);
function LoadEvents() {
global $oActions;
foreach($oActions as $strActionName => $array) {
eval( 'function ' . $strActionName . '() {
SampleEvents(\'' . $strActionName . '\');
}'
);
add_action('sampletask_' . md5($strActionName), $strActionName);
if (!wp_next_scheduled( 'sampletask_' . md5($strActionName)))
wp_schedule_single_event(time() + $oActions[$strActionName]['interval'], 'sampletask_' . md5($strActionName));
}
}
function SampleEvents($strActionName) {
global $oActions;
// just log for a demo
$file = __DIR__ . '/log.html';
$current = date('l jS \of F Y h:i:s A') . ': ' . $strActionName . ', ' . $oActions[$strActionName]['value'] . '<br />' . PHP_EOL;
file_put_contents($file, $current, FILE_APPEND);
wp_schedule_single_event(time() + $oActions[$strActionName]['interval'], 'sampletask_' . md5($strActionName));
}
同样的功能也可以通过__call()
.
/* Plugin Name: Sample Action Hooks */
add_action('init', create_function( '', '$oSampleEvents = new SampleEvents;' ));
class SampleEvents {
public $oActions = array( 'a' => array('interval' => 10, 'value' => 'hi'),
'b' => array('interval' => 30, 'value' => 'hello'),
'c' => array('interval' => 60, 'value' => 'bye')
);
function __construct() {
foreach($this->oActions as $strActionName => $arrAction) {
add_action('sampletask_' . md5($strActionName), array(&$this, $strActionName));
if (!wp_next_scheduled( 'sampletask_' . md5($strActionName)))
wp_schedule_single_event(time() + $this->oActions[$strActionName]['interval'], 'sampletask_' . md5($strActionName));
}
}
function __call($strMethodName, $arguments) {
// just log for a demo
$file = __DIR__ . '/log.html';
$current = date('l jS \of F Y h:i:s A') . ': ' . $strMethodName . ', ' . $this->oActions[$strMethodName]['value'] . '<br />' . PHP_EOL;
file_put_contents($file, $current, FILE_APPEND);
wp_schedule_single_event(time() + $this->oActions[$strMethodName]['interval'], 'sampletask_' . md5($strMethodName));
}
}