使用全局变量在两个函数之间传递字符串的问题
I'm trying to pass $old from getOldText to reEdit with globals, but its not working. I can't call getOldText from inside reEdit, because by the time that occurs the old text would have been overwritten by the edit.
$old = "INITIAL";
function reEdit() {
global $old;
//removed code creating article object to simplify
$new = $article->getRawText();
$article->doEdit( "$new <-new old -> $old"); //PROBLEM HERE, returns as INITIAL
return true;
}
function getOldText() {
global $old;
//removed code creating article object to simplify
$old = $article->getRawText();
return true;
}
$wgHooks['EditFormInitialText'][] = array('getOldText');
$wgHooks['ArticleSaveComplete'][] = array('reEdit');
The problem is in the line indicated - $old is not passed to it despite being global.
The $wgHooks are MediaWiki code that call my functions when an article is starting to be edited and saved, respectively. For those who are familiar with mediawiki code, I'm just trying to get the text from before an edit was performed.
The reason your global variable is not persisting the value is because your two functions are not both being run in the same HTTP request. EditFormInitialText
is called when the edit form is being generated, and may not actually be run at all in some cases. ArticleSaveComplete
is called on a later submission, when the new version of the article is actually finished being saved.
You may be able to do what you are wanting to do with the ArticleSave
hook instead of EditFormInitialText
.
Where is the $old variable being set initially? I think the issue might be scoping, and that you shouldn't have the 'global' word in front of the initial $old outside of the functions. Without seeing more of the code, there's no way to be sure.
I know this is not standard way but we can still try using $_GET to store old data. This way we can eliminate all file/class specific scoping issue.
$_GET['old'] = 'INITIAL';
function reEdit() {
//removed code creating article object to simplify
$new = $article->getRawText();
$article->doEdit( "$new ".$_GET['old']); //PROBLEM HERE, returns as INITIAL
return true;
}
function getOldText() {
//removed code creating article object to simplify
$_GET['old'] = $article->getRawText();
return true;
}
$wgHooks['EditFormInitialText'][] = array('getOldText');
$wgHooks['ArticleSaveComplete'][] = array('reEdit');
Try above and see it that works, if it works then it's problem of scoping we need to check. Otherwise you need to revisit MediaWiki docs.
BTW, first line on your code is not required.