【发布时间】:2010-11-21 00:04:05
【问题描述】:
代码:
if ( $_GET['tab'] == 'newest' ) {
// Go through each question
foreach( array_reverse( $end_array, true ) as $tags_and_Qid['question_id'] => $titles_and_Qid['title'] )
{
// Grab the title for the first array
$title = $titles [ $tags_and_Qid['question_id'] ] ['title'];
// Grab the tags for the question from the second array
$tags = $end_array [ $tags_and_Qid['question_id'] ] ['tag'];
// Grab the username for the question from the second array
$username = $usernames [ $tags_and_Qid['question_id'] ] ['username'];
--- cut ----
}
}
我需要经常使用此代码。唯一的区别是第一个示例中的array_reverse (..., true)。
我已尝试通过创建函数organize_question 来解决此问题。我失败了:
function organize_questions ( $tab ) {
if ( $_GET['tab'] == 'newest' ) {
echo ( "array_reverse ( $end_array , true )" );
// Problem here!
}
if ( $_GET['tab'] == 'oldest' ) {
echo ( "$end_array" );
// this does not work
} else {
echo ( "array_reverse ( $end_array , true )" );
// Problem here!
}
}
然后我将代码中的相关行更改为:
foreach( organize_question( $tab ) as $tags_and_Qid['question_id'] => $titles_and_Qid['title'] )
问题在于将变量从一个函数转移到另一个函数。
我试图将所有必要的变量放在函数的参数中,但一切都被破坏了,因为这个函数有很多依赖项。
我是 PHP 新手,所以必须有比我尝试的更简单的方法。
【问题讨论】:
-
重用代码的最佳方式?不使用PHP!哦,我的孩子,我的孩子......
标签: php code-reuse